C Primer Plus学习 四十二 fprintf ()和 fscanf ()函数
来源:互联网 发布:淘宝生意参谋情报竞争 编辑:程序博客网 时间:2024/05/14 05:30
文件I/O函数fprintf ()和fscanf ()的工作方式与printf ()和scanf ()相似,区别在于前两者需要 第一个参数来指定合适的文件。前面您已经使用过fprintf ()。程序清单丨3.3演示了这两个文件I/O函数 以及rewind ()函数的使用。
DOS环境下的运行示例:/* addaword.c --使用 fprintf ()、fscanf (),和 rewind ()函数 */
#include <stdio.h>
#include <stdlib.h>
#define MAX 40
int main(void)
{
FILE *fp;
char words[MAX];
if((fp=fopen("words","a+"))==NULL)
{
fprintf(stdout,"Can't open \"words\" file.\n");
exit(1);
}
puts ("Enter words Co add to the file; press the Enter");
puts ("key at the beginning of a line to terminate.");
while (gets (words) != NULL && words[0] != '\0')
fprintf(fp, "%s", words);
puts ("File contents:");
rewind (fp); /*回到文件的开始处*/
while (fscanf(fp,"%s",words) == 1)
puts(words);
if (fclose(fp)!=0)
fprintf (stderr, "Error closing file\n");
return 0;
}
通过该程序可以向文件中加入单词。使用” a+”模式,程序可以对文件进行读写操作。第一次使用该程 序的时候会创建一个wonkly文件以供添加单词。在随后的使用中,可以向以前的内容后面添加(追加) 单词。追加模式只能向文件结尾添加内容,但”a+"模式可以读取整个文件。rewind ()命令使程序回到文 件开始处,这样最后的while循环就可以打印文件的内容。注意rewind ()函数接受一个文件指针参数。Enter words to add to the file; press the Enter key at the beginning of a line to terminate.
The fabulous progranMr(enter]
[enter】
File contents:
The
fabulous
programmer
C>addaword
Enter words to add to the file; press the Enter key at the beginning of a line to terminate, enchanted the[enter] large[enter]
File contents:
The
fabulous
programmer
enchanted
the
large
如果您键入一个空行,gets ()函数将数组的第一个元素置为空字符,程序据此来终止循环。
- C Primer Plus学习 四十二 fprintf ()和 fscanf ()函数
- fprintf和fscanf函数
- fprintf函数和fscanf函数
- 嵌入式 fprintf和fscanf函数
- C语言fscanf和fprintf
- C语言中的文件格式化读写函数:fprintf和fscanf
- C语言中的文件格式化读写函数:fprintf和fscanf
- C文件操作函数fscanf和fprintf的使用
- linux下C函数---fscanf和fprintf的使用
- c语言中格式化读写函数fscanf()和fprintf()
- 文件函数之fscanf和fprintf
- 格式化读写函数:fscanf和fprintf
- c语言中fscanf和fprintf
- 关于sscanf,fprintf和fscanf,fprintf函数的应用
- fprintf/fscanf函数分析
- 学习《C Primer Plus》---存储类和函数
- C Primer Plus学习 二十 函数、数组和指针
- C Primer Plus学习 五十 函数和指针
- CSSTIPS
- jquery基本语法
- 【知识点待整理】工作中遇到的问题难点
- Android Studio错误总结
- margin和padding的区别
- C Primer Plus学习 四十二 fprintf ()和 fscanf ()函数
- MVP 框架模式(学习笔记)
- mysqldump 一些参数体验
- java.lang.NoClassDefFoundError: org/aspectj/weaver/tools/PointcutDesignatorHandler at java.lang.Cla
- 机器学习——GBDT/xgboost
- 自定义类型
- 后台执行命令 -- &和nohup
- yii用户注册的表单验证
- C语言32个关键字