使用fwrite()函数和fprintf()函数输出数据到文件时的区别

时间:2023-03-09 08:16:49
使用fwrite()函数和fprintf()函数输出数据到文件时的区别

使用书上的一个课后题为例

有5个学生,每个学生有3门课的成绩,从键盘输入学生数据(包括学号,姓名,3们课程成绩),计算出每个学生的平均成绩,将原有数据和计算出的平均分数存放在磁盘文件“stud”中。

屡次调试后,我编好的程序:

 #include<stdio.h>
#include<stdlib.h>
#define FWRITE int main(){
setbuf(stdout,NULL);
struct student
{
int NUM;
char name[];
int scores[];
float aver;
};
FILE *fp;
struct student stus[],test[];
int i,j;
int num; printf("Input the data of students:\n");
for(i=;i<;i++)
scanf("%d%s%d%d%d",&stus[i].NUM,stus[i].name,
&stus[i].scores[],&stus[i].scores[],&stus[i].scores[]); for(i=;i<;i++)
{
num=;
for(j=;j<;j++)
num+=stus[i].scores[j];
stus[i].aver=num/3.0;
} if((fp=fopen("stud.txt","wb+"))==NULL)
{
printf("cannot open the file.\n");
exit();
}
#ifdef FWRITE
for(i=;i<;i++)
{
if(fwrite(&stus[i],sizeof(struct student),,fp)!=)
printf("file write error\n");
} printf("Read the data from the file.\n");
rewind(fp);
for(i=;i<;i++)
{
fread(&test[i],sizeof(struct student),,fp);
printf("%d,%s,%d,%d,%d,%.2f\n",test[i].NUM,test[i].name,test[i].scores[],
test[i].scores[],test[i].scores[],test[i].aver);
}
#else
for(i=;i<;i++)
fprintf(fp,"%d,%s,%d,%d,%d,%.2f\r\n",stus[i].NUM,stus[i].name,stus[i].scores[],
stus[i].scores[],stus[i].scores[],stus[i].aver);
#endif
fclose(fp);
return ;
}

程序中使用条件编译在两种方法中进行转换。

默认使用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"方式。