使用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:
");
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.
");
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
");
42     }
43 
44     printf("Read the data from the file.
");
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
",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
",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 "和"%d,%s,%d,%d,%d,%.2f "两种方式均可(系统会自动把 转换为 )

  2) 打开方式为二进制方式“wb+”时,只能使用"%d,%s,%d,%d,%d,%.2f "方式。

原文地址:https://www.cnblogs.com/Camilo/p/3380171.html