fprintf往文件中写格式化数据
函数原型
#include<stdio.h>
int fprintf(FILE *stream,const char *format,...);
实例
#include<stdio.h>
/*
*需求:让用户输入学员的姓名、年龄
并把这些信息按照如下格式保存到文件students.txt
姓名:张飞 年龄:38
姓名:刘备 年龄:40
*/
int main(void){
char name[32];
char c;
int age;
FILE *file;
file = fopen("students.txt","w");
if (! file){
printf("文件打开失败\n");
return 1;
}
while(1){
//提示用户输入
printf("请输入学员的姓名:");
scanf("%s",name);
printf("请输入%s的年龄:",name);
scanf("%d",&age);
//清空输入缓冲区
fflush(stdin);
//while((c=getchar()) !='\n');
//按指定格式,保存到文件
fprintf(file,"姓名:%s\t\t年龄:%d\n",name,age);
printf("还需要继续输入吗?Y/N\n");
scanf("%c",&c); //读取了以前残留的‘\n’
if(c=='Y' || c=='y'){
continue;
}else{
break;
}
}
fclose(file);
return 0;
}