使用fwrite()函數和fprintf()函數輸出數據到文件時的區別


使用書上的一個課后題為例

有5個學生,每個學生有3門課的成績,從鍵盤輸入學生數據(包括學號,姓名,3們課程成績),計算出每個學生的平均成績,將原有數據和計算出的平均分數存放在磁盤文件“stud”中。

屢次調試后,我編好的程序:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #define FWRITE
 4 
 5 int main(){  6  setbuf(stdout,NULL);  7     struct student  8  {  9         int NUM; 10         char name[20]; 11         int scores[3]; 12         float aver; 13  }; 14     FILE *fp; 15     struct student stus[5],test[5]; 16     int i,j; 17     int num; 18 
19     printf("Input the data of students:\n"); 20     for(i=0;i<5;i++) 21         scanf("%d%s%d%d%d",&stus[i].NUM,stus[i].name, 22                 &stus[i].scores[0],&stus[i].scores[1],&stus[i].scores[2]); 23 
24     for(i=0;i<5;i++) 25  { 26         num=0; 27         for(j=0;j<3;j++) 28             num+=stus[i].scores[j]; 29         stus[i].aver=num/3.0; 30  } 31 
32     if((fp=fopen("stud.txt","wb+"))==NULL) 33  { 34         printf("cannot open the file.\n"); 35         exit(0); 36  } 37 #ifdef FWRITE 38     for(i=0;i<5;i++) 39  { 40         if(fwrite(&stus[i],sizeof(struct student),1,fp)!=1) 41             printf("file write error\n"); 42  } 43 
44     printf("Read the data from the file.\n"); 45  rewind(fp); 46     for(i=0;i<5;i++) 47  { 48         fread(&test[i],sizeof(struct student),1,fp); 49         printf("%d,%s,%d,%d,%d,%.2f\n",test[i].NUM,test[i].name,test[i].scores[0], 50                 test[i].scores[1],test[i].scores[2],test[i].aver); 51  } 52 #else
53     for(i=0;i<5;i++) 54         fprintf(fp,"%d,%s,%d,%d,%d,%.2f\r\n",stus[i].NUM,stus[i].name,stus[i].scores[0], 55                     stus[i].scores[1],stus[i].scores[2],stus[i].aver); 56 #endif
57  fclose(fp); 58     return 0; 59 }

程序中使用條件編譯在兩種方法中進行轉換。

默認使用fwrite方式進行輸出,把第三行注釋掉以后就是使用fprintf進行輸出。

下面說明兩者的用法:

1.fwrite

a.打開文件時,必須使用二進制的方式,“wb+”才可以,如果使用“wb”,通過fread()函數讀出並printf到終端時,會出現亂碼。

b.向文件輸出數據后,不能通過雙擊打開“stud.txt”來查看數據,里面肯定是亂碼,如果要檢驗fwrite是否輸出成功,只有通過fread函數讀出后再printf到終端查看。

2.fprintf

a.向文件輸出數據后,可以通過雙擊打開“stud.txt”來查看數據。

b.如果在文件里面要換行:

  1) 打開方式為文本文件方式“w+”時,使用"%d,%s,%d,%d,%d,%.2f\n"和"%d,%s,%d,%d,%d,%.2f\r\n"兩種方式均可(系統會自動把\n轉換為\r\n)

  2) 打開方式為二進制方式“wb+”時,只能使用"%d,%s,%d,%d,%d,%.2f\r\n"方式。


免責聲明!

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



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