C語言 fread()與fwrite()函數說明與示例


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數據到文件

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 int main ()
 4 {
 5   FILE * pFile;
 6   int buffer[] = {1, 2, 3, 4};
 7   if((pFile = fopen ("myfile.txt", "wb"))==NULL)
 8   {
 9       printf("cant open the file");
10       exit(0);
11   }
12   //可以寫多個連續的數據(這里一次寫4個)
13   fwrite (buffer , sizeof(int), 4, pFile);
14   fclose (pFile);
15   return 0;
16 }
View Code

  (2)讀取int數據

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int main () {
 5     FILE * fp;
 6     int buffer[4];
 7     if((fp=fopen("myfile.txt","rb"))==NULL)
 8     {
 9       printf("cant open the file");
10       exit(0);
11     }
12     if(fread(buffer,sizeof(int),4,fp)!=4)   //可以一次讀取
13     {
14         printf("file read error\n");
15         exit(0);
16     }
17 
18     for(int i=0;i<4;i++)
19         printf("%d\n",buffer[i]);
20     return 0;
21 }
View Code

 執行結果:

5.讀寫結構體數據

  (1)寫結構體數據到文件

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 typedef struct{
 5     int age;
 6     char name[30];
 7 }people;
 8 
 9 int main ()
10 {
11     FILE * pFile;
12     int i;
13     people per[3];
14     per[0].age=20;strcpy(per[0].name,"li");
15     per[1].age=18;strcpy(per[1].name,"wang");
16     per[2].age=21;strcpy(per[2].name,"zhang");
17 
18     if((pFile = fopen ("myfile.txt", "wb"))==NULL)
19     {
20         printf("cant open the file");
21         exit(0);
22     }
23 
24     for(i=0;i<3;i++)
25     {
26         if(fwrite(&per[i],sizeof(people),1,pFile)!=1)
27             printf("file write error\n");
28     }
29     fclose (pFile);
30     return 0;
31 }
View Code

  (2)讀結構體數據

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 typedef struct{
 5     int age;
 6     char name[30];
 7 }people;
 8 
 9 int main () {
10     FILE * fp;
11     people per;
12     if((fp=fopen("myfile.txt","rb"))==NULL)
13     {
14       printf("cant open the file");
15       exit(0);
16     }
17 
18     while(fread(&per,sizeof(people),1,fp)==1)   //如果讀到數據,就顯示;否則退出
19     {
20         printf("%d %s\n",per.age,per.name);
21     }
22     return 0;
23 }
View Code

執行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM