您的位置:首页 > 编程语言 > C语言/C++

C语言 fread()与fwrite()函数说明与示例

2013-12-17 13:57 393 查看
1.作用

  读写文件数据块。

2.函数原型

  (1)size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

     其中,ptr:指向保存结果的指针;size:每个数据类型的大小;count:数据的个数;stream:文件指针

     函数返回读取数据的个数。

  (2)size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );

     其中,ptr:指向保存数据的指针;size:每个数据类型的大小;count:数据的个数;stream:文件指针

     函数返回写入数据的个数。

3.注意

  (1)写操作fwrite()后必须关闭流fclose()。


  (2)不关闭流的情况下,每次读或写数据后,文件指针都会指向下一个待写或者读数据位置的指针。

4.读写常用类型

  (1)写int数据到文件

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct{
int age;
char name[30];
}people;

int main () {
FILE * fp;
people per;
if((fp=fopen("myfile.txt","rb"))==NULL)
{
printf("cant open the file");
exit(0);
}

while(fread(&per,sizeof(people),1,fp)==1)   //如果读到数据,就显示;否则退出
{
printf("%d %s\n",per.age,per.name);
}
return 0;
}


View Code
执行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: