首页 > 试题广场 >

修改程序清单13.3中的程序,从1开始,根据加入列表的顺序为

[问答题]
修改下面的程序,从1开始,根据加入列表的顺序为每个单词编号。当再次运行程序时,确保新的单词编号接着前面的编号开始。
/* 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 to add to the files; 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;
}
推荐
/* addaword.c -- uses fprintf(), fscanf(), and rewind() */
#include <stdio.h>
#include <stdlib.h>
#define MAX 40
int main(void)
{
 FILE *fp;
 char words[MAX];
 int count = 0;
 if ((fp = fopen("wordy", "a+")) == NULL)
 {
 fprintf(stdout,"Can't open \"words\" file.\n");
 exit(1);
 }
 rewind(fp);
 while ( fgets(words,MAX-1,fp) != NULL) count++;
 puts("Enter words to 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, "%d:%s\n", count++, words);
 puts("File contents:");
 rewind(fp);           /* go back to beginning of file */
 while (fscanf(fp,"%s",words) == 1)
 puts(words);
 if (fclose(fp) != 0)
 fprintf(stderr,"Error closing file\n");
 return 0;
}

发表于 2018-05-05 21:59:39 回复(0)