您的位置:首页 > 其它

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

2013-10-21 10:54 387 查看
使用书上的一个课后题为例

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

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

 1 #include<stdio.h>
#include<stdlib.h>
#define FWRITE

int main(){
setbuf(stdout,NULL);
struct student
{
int NUM;
char name[20];
int scores[3];
float aver;
};
FILE *fp;
struct student stus[5],test[5];
int i,j;
int num;

printf("Input the data of students:\n");
for(i=0;i<5;i++)
scanf("%d%s%d%d%d",&stus[i].NUM,stus[i].name,
&stus[i].scores[0],&stus[i].scores[1],&stus[i].scores[2]);

for(i=0;i<5;i++)
{
num=0;
for(j=0;j<3;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(0);
}
#ifdef FWRITE
for(i=0;i<5;i++)
{
if(fwrite(&stus[i],sizeof(struct student),1,fp)!=1)
printf("file write error\n");
}

printf("Read the data from the file.\n");
rewind(fp);
for(i=0;i<5;i++)
{
fread(&test[i],sizeof(struct student),1,fp);
printf("%d,%s,%d,%d,%d,%.2f\n",test[i].NUM,test[i].name,test[i].scores[0],
test[i].scores[1],test[i].scores[2],test[i].aver);
}
#else
for(i=0;i<5;i++)
fprintf(fp,"%d,%s,%d,%d,%d,%.2f\r\n",stus[i].NUM,stus[i].name,stus[i].scores[0],
stus[i].scores[1],stus[i].scores[2],stus[i].aver);
#endif
fclose(fp);
return 0;
}


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

默认使用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[b]\n"和"%d,%s,%d,%d,%d,%.2f\r\n"两种方式均可(系统会自动把\n转换为\r\n)[/b]

  2) 打开方式为二进制方式“wb+”时,只能使用"%d,%s,%d,%d,%d,%.2f[b]\r\n"方式。[/b]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: