C

C 知识量:16 - 74 - 317

13.3 文件I/O><

fprintf()和fscanf()函数- 13.3.1 -

fprintf()和fscanf()函数的使用方式与printf()和scanf()函数相似,只不过,它们的第1个参数需要用于指定待处理的文件。以下是一个示例:

#include <stdio.h>
#include <stdlib.h>    // 提供 exit()的原型
#include <string.h>
#define MAX 41

int main(void) {
    FILE *fp; //文件指针
    char words[MAX];
    if ((fp = fopen("news", "a+")) == NULL) {
        fprintf(stdout, "Open news failed.\n");
        exit(EXIT_FAILURE);
    }
    puts("Please 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, "Close file failed.\n");
    system("pause");
    return 0;
}

运行结果:

Please enter words to add to the file;press the #
Key at the beginning of a line to terminate.
Hello pnotes.cn
#
File contents:
Hello
pnotes.cn
Done!

对于以上代码,使用了"a+"模式,因此,程序可以对文件进行读写操作。如果一开始,文件news不存在,则创建它。在fprintf()函数中,如果第一个参数是文件指针,比如上面的fp,那么该函数将把输入打印到文件里,实际效果就是将输入写入文件。

此外,rewind(fp);的作用是让程序回到文件的开始处。

fgets()和fputs()函数- 13.3.2 -

fgets()函数有三个参数:

  • 第1个参数表示存储输入位置的地址,属于char * 类型。

  • 第2个参数是一个整数,表示待输入字符串的大小。

  • 第3个参数是一个文件指针,指定了待读取的文件。

例如:

 fgets(arr_c, MAX, fp);

其中,arr_c是char类型数组的名称;MAX是定义的常量,表示字符串的大小;fp是指向FILE的指针。

fgets()函数读取输入,直到第1个换行符的后面,或者读到文件结尾,再或者读到MAX-1个字符时停止。然后,fgets()函数会在末尾添加一个空字符使之成为一个字符串。如果fgets()函数在读到字符上限之前就已经读完一整行,那么它会把表示行结尾的换行符放在空字符前面。fgets()函数在遇到EOF(文件结尾)时会返回NULL值。

fputs()函数有两个参数:

  • 第1个参数是字符串的地址。

  • 第2个参数是文件指针。

例如:

fputs(buf, fp);

其中,buf是字符串的地址;fp指向目标文件。

fputs()函数根据传入的地址找到字符串并写入指定的文件中。与puts()函数不同的是:fputs()函数在打印字符串时不会在其末尾添加换行符。

fgets()函数保留换行符,而fputs()函数不添加换行符,它们配合使用十分方便。