二、数据块读写函数(fread() 和 fwrite())
函数调用:
fread (buffer,size,count , fp);
fwrite(buffer,size,count,fp);
参数说明:
buffer :是一个指针。
对fread 来说,它是读入数据的存放地址。
对fwrite 来说,是要输出数据的地址(均指起始地址)。
size : 要读写的字节数。
count : 要进行读写多少个 size 字节的数据项。
fp : 文件型指针。
使用举例:
若文件以二进制形式打开:
fread(f,4,2,fp);
此函数从fp 所指向的文件中读入 2 个 4 个字节的数 据,存储到数组 f 中。
使用举例:
若有如下结构类型:
struct student_type
{char name[10];
int num;
int age;
char addr[30];}stud[40];
可以用fread 和 fwrite 来进行数据的操作:
for (i=0;i<40;i++)
fread(&stud [ i ], sizeof(struct student-type) , 1 , fp);
for (i=0;i<40,i++)
fwrite(&stud [ i ], sizeof(struct student-type) , 1 , fp);
使用举例:
例1、 从键盘输入4个学生的有关数据,然后把它们转存 到磁盘文件上去。
#include <stdio.h>
#define SIZE 4
struct student_type
{ char name[10];
int num;
int age;
char addr[15];
}stud[SIZE]; /* 定义结构 */
void save( )
{FILE *fp;
int i;
if((fp=fopen("stu-list","wb"))==NULL)
{ printf("cannot open file\n");
return;}
for(i=0;i<SIZE;i++)/* 二进制写 */
if(fwrite(&stud[i],sizeof(struct student_type),1,fp)!=1)
printf( “ file write error\n ” );/* 出错处理 */
fclose(fp); } /* 关闭文件 */
main()
{int i;
for(i=0;i<SIZE;i++)/* 从键盘读入学生信息 */
scanf("%s%d%d%s",stud[i].name,&stud[i].num,
&stud[i].age,stud[i].addr);
save( );}/* 调用 save ()保存学生信息 */
运行情况如下:
输入4个学生的姓名、学号、年龄和地址:
Z hang 1001 19 room - 101
F un 1002 20 room - 102
T an 1003 21 room - 103
L ing 1004 21 room - 104
#include <stdio.h>
#define SIZE 4
struct student_type
{ char name[10];
int num;
int age;
char addr[15];
}stud[SIZE];
main( )
{ int i;
FILE*fp;
fp=fopen("stu-list","rb");
for(i=0;i<SIZE;i++)
{fread(&stud[i],sizeof(struct student_type),1,fp);
printf("%\-10s %4d %4d %\-15s\n",stud[i].name,
stud[i].num,stud[i]. age,stud[i].addr); }
fclose (fp);}
屏幕上显示出以下信息:
Z hang 1001 19 room - 101
F un 1002 20 room - 102
T an 1003 21 room - 103
L ing 1004 21 room - 104
#include <stdio.h>
#define SIZE 4
struct student_type
{ char name[10];
int num;
int age;
char addr[15];
}stud[SIZE];
main( )
{ int i;
FILE*fp;
fp=fopen("stu-list","rb");
for(i=0;i<SIZE;i++)
{fread(&stud[i],sizeof(struct student_type),1,fp);
printf("%\-10s %4d %4d %\-15s\n",stud[i].name,
stud[i].num,stud[i]. age,stud[i].addr); }
fclose (fp);}
屏幕上显示出以下信息:
Z hang 1001 19 room - 101
F un 1002 20 room - 102
T an 1003 21 room - 103
L ing 1004 21 room - 104
如果已有的数据已经以二进制形式存储在一个磁盘文件
“stu - dat”中,要求从其中读入数据并输出到
“stu - list”文件中,可以编写一个load函数, 从磁盘文件中读二进制数据。
void load( )
{FILE *fp;int i;
if((fp=fopen("stu-dat","rb"))==NULL)
{ printf("cannot open infile\n");
return;}
for(i=0;i<SIZE;i++)
if(fread(&stud[i],sizeof(struct student_type),1,fp)!=1)
{if(feof(fp)) {fclose(fp); return;}
printf("file read error\n");}
fclose (fp) ; }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69914734/viewspace-2655145/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/69914734/viewspace-2655145/