,const char *format[,argument]....);
用于从文件格式化读取数据,若读取成功,则返回读取的数据个数,否则返回-1
int fprintf(FILE *fp,const char *format[,argument]....);
用于向文件格式化写入数据,若写入成功,则返回写入的字符个数,否则返回-1
注意:1)格式化读写和其他几种读写有很大的不同。格式化读写是以我们人所能识别的格式将数据写入文件,即若以格式化方式写入一个整型数值65,则其实是写入的两个字符'6'和'5',即占2字节,而不是4字节,但是若以块写方式写入,则其占4字节。即在使用格式化读写时系统自动进行了一些转换。
2)fprintf和fscanf函数一般成对出现,若数据是用fprintf进行写入的,则最好使用fscanf进行读取。
3)在使用fprintf函数写入时,若文件是以文本方式打开,如果参数format中包含了'\n',则最后文件中会被写入换行符;而若文件以二进制方式打开,则文件中不会被写入换行符,这点区别在上一篇博客中已经提到。
测试程序:
#include
#include
typedef struct node
{
char name[20];
double score;
int age;
}Student;
int main(void)
{
FILE *fp;
int i;
Student s1[3]={{"liudehua",85.5,45},{"zhangxueyou",79.3,47},{"guofucheng",83.4,43}};
Student s2[3];
if((fp=fopen("test.txt","wb+"))==NULL)
{
printf("can not open file\n");
exit(0);
}
for(i=0;i<3;i++)
{
printf("%d\n",fprintf(fp,"%s %lf %d\n",s1[i].name,s1[i].score,s1[i].age));
}
rewind(fp);
for(i=0;i<3;i++)
{
printf("%d\n",fscanf(fp,"%s %lf %d",s2[i].name,&s2[i].score,&s2[i].age));
}
for(i=0;i<3;i++)
{
printf("%s %lf %d\n",s2[i].name,s2[i].score,s2[i].age);
}
fclose(fp);
return 0;
}
执行结果:
22
25
24
3
3
3
liudehua 85.500000 45
zhangxueyou 79.300000 47
guofucheng 83.400000 43
Press any key to continue
文件test.txt中的内容是:

若将打开方式改成"wt+",则文件中的内容为:

而若以fread和fwrite方式进行读写时,其结果如下:
测试程序:
#include
#include
typedef struct node
{
char name[20];
double score;
int age;
}Student;
int main(void)
{
FILE *fp;
Student s1[3]={{"liudehua",85.5,45},{"zhangxueyou",79.3,47},{"guofucheng",83.4,43}};
if((fp=fopen("test.txt","wt+"))==NULL)
{
printf("can not open file\n");
exit(0);
}
fwrite(s1,sizeof(s1),1,fp);
fclose(fp);
return 0;
}
则文件中的内容为:

从这里就可以看出格式化读写跟其他方式的区别。
测试程序:
#include
#include
int main(void)
{
FILE *fp;
int n=32768;
if((fp=fopen("test.txt","wt+"))==NULL)
{
printf("can not open file\n");
exit(0);
}
fwrite(&n,sizeof(int),1,fp);
fclose(fp);
return 0;
}
执行后,用二进制方式打开文件:

而32768的二进制为00000000100000000000000即00 80 00 00,内容占4个字节。
而
#include
#include
int main(void)
{
FILE *fp;
int n=32768;
if((fp=fopen("test.txt","wt+"))==NULL)
{
printf("can not open file\n");
exit(0);
}
fprintf(fp,"%d",n);
fclose(fp);
return 0;
}
执行的结果:

即用fprintf写入的是51,50,55,54,56,即跟字符'3','2','7','6','8'各自对应的整数值,内容占5个字节
作者 海 子