文件I/O函数fprintf()和fscanf()的工作方式与printf()和scanf()类似,区别在于前者第一个参数需要一个指定待处理的文件。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 41
int main(void)
{
FILE *fp;
char words[MAX];
if ((fp = fopen("wordy", "a+")) == NULL)
{
fprintf(stdout, "Can`t open \"wordy\" file.\n");
exit(EXIT_FAILURE);
}
puts("Enter words to add to the file;press the #");
puts("key at the beginning of a line to terminate.");
while ((fscanf(stdin, "%40s", words) == 1) && (words[0] != '#'))
fprintf(fp, "%s\n", words);
puts("File contents:");
rewind(fp); //返回到文件开始处
while (fscanf(fp, "%s", words) == 1)
puts(words);
puts("Done!");
if (fclose(fp) != 0)
fprintf(stderr, "Error closing file\n");
return 0;
}
运行结果案例:
该程序可以在文件中添加单词。使用"a+"模式,程序可以对文件进行读写操作。首次使用该程序,它将创建wordy文件,以便把单词存入其中。随后再使用该程序,可以在wordy文件后面添加单词。虽然"a+"模式支允许在文件末添加内容,但是该模式下可以读整个文件。rewind()函数让程序回到文件开始处,方便while循环打印整个文件的内容。