fread函数和fwrite函数 fseek()函数和ftell()函数

1.函数功能

用来读写一个数据块。

2.一般调用形式

fread(buffer,size,count,fp);

fwrite(buffer,size,count,fp);

3.说明

(1)buffer:是一个指针,对fread来说,它是读入数据的存放地址。对fwrite来说,是要输出数据的地址。

(2)size:要读写的字节数;

(3)count:要进行读写多少个size字节的数据项;

(4)fp:文件型指针。

注意:1

完成次写操(fwrite())作后必须关闭流(fclose());

2

完成一次读操作(fread())后,如果没有关闭流(fclose()),则指针(FILE *

fp)自动向后移动前一次读写的长度,不关闭流继续下一次读操作则接着上次的输出继续输出;

3 fprintf() : 按格式输入到流,其原型是int

fprintf(FILE *stream, const char *format[, argument,

...]);其用法和printf()相同,不过不是写到控制台,而是写到流罢了。注意的是返回值为此次操作写入到文件的字节数。如int c

= fprintf(fp, "%s %s %d %f", str1,str2, a, b) ;str1:10字节;str2:

10字节;a:2字节;b:8字节,c为33,因为写入时不同的数据间自动加入一个空格。

文件使用之后一定要关闭,否则将不能正确显示内容.fwrite:读入两个学生信息然后用fwrite存入文件

fread:用fread从文件中读出学生信息。

fwrite.c

#include

#define SIZE 2

struct student_type

{

char name[10];

int num;

int age;

char addr[10];

}stud[SIZE];

void save()

{

FILE *fp;

int i;

if((fp=fopen("stu_list","wb"))==NULL)

{

printf("cant open the file");

exit(0);

}

for(i=0;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

{

scanf("%s%d%d%s",&stud[i].name,&stud[i].num,&stud[i].age,&stud[i].addr);

save();

}

for(i=0;i

{

printf("%s,%d,%d",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);

}

}

fread.c

#include

#define SIZE 2

struct student_type

{

char name[10];

int num;

int age;

char addr[10];

}stud[SIZE];

void read()

{

FILE *fp;

int i;

if((fp=fopen("stu_list","rb"))==NULL)

{

printf("cant open the file");

exit(0);

}

for(i=0;i

{

if(fread(&stud[i],sizeof(struct

student_type),1,fp)!=1)

printf("file

write error\n");

}

fclose(fp);

}

main()

{

int i;

read();

for(i=0;i

{

printf("%s,%d,%d,%s",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);

printf("\n");

}

}

fseek函数是用来设定文件的当前读写位置:

函数原型:int fseek(FILE *fp,long offset,int origin);

函数功能:把fp的文件读写位置指针移到指定的位置.

fseek(fp,20,SEEK_SET);

//意思是把fp文件读写位置指针从文件开始后移20个字节.

ftell函数是用来获取文件的当前读写位置;

函数原型: long ftell(FILE *fp)

函数功能:得到流式文件的当前读写位置,其返回值是当前读写位置偏离文件头部的字节数.

ban=ftell(fp);

//是获取fp指定的文件的当前读写位置,并将其值传给变量ban.

fseek函数与ftell函数综合应用:

分析:可以用fseek函数把位置指针移到文件尾,再用ftell函数获得这时位置指针距文件头的字节数,这个字节数就是文件的长度.

view plaincopy to clipboardprint?#include

 main() { FILE

*fp; char

filename[80]; long

length; printf("Input the file

name:"); gets(filename); fp=fopen(filename,"rb"); if(fp==NULL) printf("file not

found!\n"); else { fseek(fp,OL,SEEK_END); length=ftell(fp); printf("the file length

bytes\n",length); fclose(fp); } }

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐