C语言数据块读写函数:fread和fwrite

1.fread和fwrite函数的定义

  size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *fp);
  size_t fread(const void *ptr, size_t size, size_t nmemb, FILE *fp); 
 
 (1)ptr:缓冲区的首地址,对fread来说,它是读入数据的存放地址;对fwrite来说,是要输出数据的地址。
 (2)size:要读写的字节数。
 (3)nmemb:要进行读写多少个size字节的数据项。
 (4)fp:文件结构指针
 (5)返回值是实际写入的nmemb数目。

2.一个例子
 
 1 #include <stdio.h>
 2 
 3 struct Student
 4 {
 5     int id;
 6     char name[20];
 7 };
 8 
 9 int main()
10 {
11     FILE *pRead, *pWrite;
12     struct Student stu[3] = {{1, "zhangsan"}, {2, "lisi"}, {3, "wangwu"}};
13     
14     //以二进制形式打开文件,用于写入
15     pWrite = fopen("stu_bin.txt", "wb");
16     if(NULL != pWrite)
17     {
18         int count = fwrite(stu, sizeof(struct Student), 3, pWrite);
19         printf("Write %d students!\n", count);
20         fclose(pWrite);//关闭文件指针,否则无法读取文件
21         
22         //以二进制形式打开文件,用于读取
23         pRead = fopen("stu_bin.txt", "rb");
24         if(NULL != pRead)
25         {
26             struct Student buf[3];
27             struct Student *tmp = buf;
28             
29             while(!feof(pRead))
30             {
31                 int i = fread(tmp, sizeof(struct Student), 1, pRead);
32                 printf("%d ", i);//应该依次输出1,1,1,0
33                 tmp++;
34             }
35             
36             int i = 0;
37             printf("\n");
38             for(; i < count; i++)
39             {
40                 printf("%d\t%s\n", buf[i].id, buf[i].name);
41             }
42             
43             fclose(pRead);
44         }
45     }
46     
47     return 0;
48 }

输出结果:



posted @ 2012-10-02 20:48  wind4869  阅读(540)  评论(0)    收藏  举报