文件I/O:fprintf()和fscanf()函数

该程序可以在文件中添加单词。

/*
 * @Author: Your name
 * @Date:   2020-03-15 21:32:33
 * @Last Modified by:   Your name
 * @Last Modified time: 2020-03-15 21:34:43
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 41
int main()
{
    FILE *fp;
    char words[MAX];
    if((fp=fopen("wordy.txt","a+"))==NULL)
    {
        fprintf(stdout,"Cant'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");
    }
    getchar();
    return 0;
}

该程序可以在文件中添加单词。使用"a+“模式,程序可以对文件进行读写操作。首次使用该程序,它将创建wordy文件,以便把单词存放在其中。随后再使用该程序,就可以在wordy文件中添加单词。虽然”a+"模式只允许在文件末尾添加内容,但是该模式可以读整个文件。rewind()函数让程序回到文件开始的地方,方便while循环打印整个内容。注意,rewind()函数只接受一个文件指针作为参数。

发布了84 篇原创文章 · 获赞 18 · 访问量 5805

猜你喜欢

转载自blog.csdn.net/qq_44486550/article/details/104896386
今日推荐