C Primer Plus学习 四十二 fprintf ()和 fscanf ()函数

来源:互联网 发布:淘宝生意参谋情报竞争 编辑:程序博客网 时间:2024/05/14 05:30

        文件I/O函数fprintf ()和fscanf ()的工作方式与printf ()和scanf ()相似,区别在于前两者需要 第一个参数来指定合适的文件。前面您已经使用过fprintf ()。程序清单丨3.3演示了这两个文件I/O函数 以及rewind ()函数的使用。

/* 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;

}

DOS环境下的运行示例:

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

        通过该程序可以向文件中加入单词。使用” a+”模式,程序可以对文件进行读写操作。第一次使用该程 序的时候会创建一个wonkly文件以供添加单词。在随后的使用中,可以向以前的内容后面添加(追加) 单词。追加模式只能向文件结尾添加内容,但”a+"模式可以读取整个文件。rewind ()命令使程序回到文 件开始处,这样最后的while循环就可以打印文件的内容。注意rewind ()函数接受一个文件指针参数。
       如果您键入一个空行,gets ()函数将数组的第一个元素置为空字符,程序据此来终止循环。




0 0
原创粉丝点击