【FROM C 语言实战105例中的第37例 随机读写文件】
/*随机读写文件第37例*/
/*来源于C语言实战105例*/
#include<stdio.h>
#include <stdlib.h>
#define NUM 3
int main(void)
{
FILE *fp1;
int i,err;
struct rec
{
char id[10];
char name[15];
char department[15];
}record[NUM];
printf("***********************************************************\n");
printf("** This program is to show the random file input & output**\n");
printf("***********************************************************\n");
/* 只写打开或新建一个二进制文件;只允许写数据。*/
if ((err=fopen_s(&fp1,"d:\\infile.txt","wb"))!=0)
{
fprintf_s(stderr,"cannot open file");
exit(1);
}
for (i=0;i<NUM;i++)
{
printf("please input id:");
fscanf_s(stdin,"%s",record[i].id,10);
printf("Please input name:");
fscanf_s(stdin,"%s",record[i].name,15);
printf("Please input department:");
fscanf_s(stdin,"%s",record[i].department,15);
fwrite(&record[i],sizeof(struct rec),1,fp1); //成块写入
}
fclose(fp1);
/*rb+ 读写打开一个二进制文件,允许读数据。*/
if ((err=fopen_s(&fp1,"d:\\infile.txt","rb+"))!=0)
{
fprintf_s(stderr,"cannot open file\n");
exit(1);
}
printf("************************************\n");
printf("%-10s%-15s%-15s\n","id","name","department");
printf("************************************\n");
/*显示文件全部内容*/
for (i=0;i<NUM;i++)
{
fread(&record[i],sizeof(struct rec),1,fp1);
printf("%-10s%-15s%-15s\n",record[i].id,record[i].name,record[i].department);
}
/*以下进行文件的随机读写*/
fseek(fp1,2*sizeof(struct rec),0); //定位文件指针指向第三条记录
fwrite(&record[1],sizeof(struct rec),1,fp1);
/*在第三条记录处写入第二条记录*/
rewind(fp1); //移动文件指针到指针头 //相当于fseek(fp1,0L,SEEK_SET);
printf("************************************\n");
printf("%-10s%-15s%-15s\n","id","name","department");
printf("************************************\n");
for (i=0;i<NUM;i++)
{
fread(&record[i],sizeof(struct rec),1,fp1);
printf("%-10s%-15s%-15s\n",record[i].id,record[i].name,record[i].department);
}
fclose(fp1);
system("pause");
return 0;
}