容。
13.4.3 数据块读写函数 fread 和 fwtrite
C语言还提供了用于整块数据的读写函数。可用来读写一组数据,如一个数组元素,一
个结构变量的值等。
读数据块函数调用的一般形式为:
fread(buffer,size,count,fp);
写数据块函数调用的一般形式为:
fwrite(buffer,size,count,fp);
其中:
buffer 是一个指针,在 fread 函数中,它表示存放输入数据的首地址。在 fwrite 函数
中,它表示存放输出数据的首地址。
size 表示数据块的字节数。
count 表示要读写的数据块块数。
fp 表示文件指针。
例如:
fread(fa,4,5,fp);
其意义是从 fp 所指的文件中,每次读 4 个字节(一个实数)送入实数组 fa 中,连续读 5 次,
即读 5 个实数到 fa 中。
【例 13.6】从键盘输入两个学生数据,写入一个文件中,再读出这两个学生的数据显示在屏
幕上。
#include
struct stu
{
char ncom[10];
int num;
int age;
char addr[15];
}boya[2],boyb[2],*pp,*qq;
main()
{
FILE *fp;
char ch;
int i;
pp=boya;
qq=boyb;
if((fp=fopen("d:\\jrzh\\example\\stu_list","wb+"))==NULL)
{
printf("Cannot open file strike any key exit!");
getch();
exit(1);
}
printf("\ninput data\n");
for(i=0;i<2;i++,pp++)
scanf("%s%d%d%s",pp->ncom,&pp->num,&pp->age,pp->addr);
pp=boya;
fwrite(pp,sizeof(struct stu),2,fp);
rewind(fp);
fread(qq,sizeof(struct stu),2,fp);
printf("\n\nncom\tnumber age addr\n");
for(i=0;i<2;i++,qq++)
printf("%s\t%5d%7d %s\n",qq->ncom,qq->num,qq->age,qq->addr);
fclose(fp);
}
本例程序定义了一个结构 stu,说明了两个结构数组