
查阅相关资料,汇总如下:
#include <stdio.h>
#include <stdlib.h> int main()
{
char money= 's';
char a ='w';
char b ='e';
char day='t'; FILE *fp = fopen("a.txt", "a+");//打开并在指定地点创建只写文件。
/*
FILE *fp = fopen("路径","写入模式");
"w" => 创建并写入(覆盖式写入)
"a" => 创建并写入(接续式写入)
"a+" => 创建并写入(分行式写入)
*/ fprintf(fp,"%c,%c,%c,%c,%c\n",money,a,b,b,day);//使用fprintf 将输出端口变更为 文档
fclose(fp);//关闭指定文件 return ;
}
欢迎参考
实例分析:
需求:让用户输入学员的姓名、年龄,
并把这些信息按照如下格式,保存到文件 students.txt
例:
姓名:刘备 年龄:38
姓名:张飞 年龄:35
#include <stdio.h> int main(){
char name[];
int age;
FILE *file;
char c; file = fopen("students.txt","w");
if(!file){
printf("文件打开失败\n");
return ;
} /*
分析:
用户输入:
Rose
31
输入缓冲区:
'R' 'o' 's' 'e' '\n' '31' '\n'
当缓冲区的数据存入数组后,输入缓冲区内还存留'\n',%d默认跳过读到整数
*/ while(){
//提示用户输入
printf("请输入学员姓名:");
scanf("%s",name);//Rose printf("请输入%s的年龄:",name);
scanf("%d", &age);//31 //按照指定格式保存到文件
fprintf(file,"姓名:%s\t年龄:%d\n",name,age); //清空输入缓冲区
fflush(stdin);//fflush 刷新
/*或者:
while((c=getchar()) != '\n');
*/ printf("还需要继续输入吗?Y/N\n");
scanf("%c", &c);//如没有清空输入缓冲区,将读取了以前残留的'\n'
if(c == 'y' || c == 'Y'){
continue;//继续输入
}else{
break;
}
} fclose(file); return ;
}
fprintf 往文件中写格式化数据
函数原型:
#include <stdio.h>
int fprintf( FILE *stream, const char *format, ... );
Demo1:
#include <stdio.h> int main(){
//格式字符串
fprintf(file,"name:%s,age:%d\n","zhangshan","");
return ;
}
Demo2:
while(){
//提示用户输入
printf("请输入学员姓名:");
scanf("%s",name);//Rose
printf("请输入%s的年龄:",name);
scanf("%d", &age);//
getchar();//将多余回车符读取掉
//按照指定格式保存到文件
fprintf(file,"姓名:%s\t年龄:%d\n",name,age);
printf("还需要继续输入吗?Y/N\n");
scanf("%c", &c);//如没有添加getchar,将读取了以前残留的'\n'
if(c == 'y' || c == 'Y'){
continue;//继续输入
}else{
break;
}
}
版权声明: 伍悦匿匿