目录
1 标准I/O – 格式化输出
2 标准I/O – 格式化输入
3 小结
4 标准I/O – 思考和练习
#include
int printf(const char *fmt, …);
int fprintf(FILE *stream, const char *fmt, …);
int sprintf(char *s, const char *fmt, …);
成功时返回输出的字符个数;出错时返回EOF
示例:以指定格式 “年-月-日” 分别写入文件和缓冲区
int year, month, date;
FILE *fp;
char buf[64];
year = 2014; month = 10; date = 26;
fp = fopen(“test.txt”, “a+”);
fprintf(fp, “%d-%d-%d\n”, year, month, date);
sprintf(buf, “%d-%d-%d\n”, year, month, date);
示例:
#include "stdio.h"
int main(int argc,char *argv[])
{
FILE *fp;
char buff[100];
int year=2021;
int month=10;
int day=1;
sprintf(buff,"%d-%d-%d\n",year,month,day); //写入字符串中
printf("%s",buff);
fp=fopen("ftest.txt","w");
if(fp==NULL){
perror("fopen");
return 0;
}
fprintf(fp,"%d-%d-%d\n",year,month,day); //写入文件中
fclose(fp);
}
int fscanf(FILE *stream, const char *format, ...);
int sscanf(const char *str, const char *format, ...);
示例
#include "stdio.h"
int main(int argc,char *argv[]){
char buf[100]={0};
int year=2021;
int month= 10;
int day=1;
int syear;
int smonth;
int sday;
sprintf(buf,"%d-%d-%d",year,month,day);
printf("%s\n",buf);
sscanf(buf,"%d-%d-%d",&syear,&smonth,&sday);
printf("%d,%d,%d\n",syear,smonth,sday);
}
示例
#include "stdio.h"
int main(int argc,char *argv[]){
FILE *fp;
int year;
int month;
int day;
fp=fopen("ftest.txt","r");
if(fp==NULL){
perror("fopen");
return 0;
}
fscanf(fp,"%d-%d-%d",&year,&month,&day);
printf("%d,%d,%d\n",year,month,day);
fclose(fp);
}
格式化输入输出用到了哪些函数?分别有什么作用?
每隔1秒向文件test.txt中写入当前系统时间,格式如下:
1, 2014-10-15 15:16:42
2, 2014-10-15 15:16:43
该程序无限循环,直到按Ctrl-C中断程序
每次执行程序时,系统时间追加到文件末尾,序号递增
1, 2014-10-15 15:16:42
2, 2014-10-15 15:16:43
3, 2014-10-16 11:35:07
4, 2014-10-16 11:35:08
提示
sleep()实现程序睡眠
以何种方式打开流?
流的缓冲类型对文件写入的影响