fgets()参数有关问题
fgets()参数问题。//lianxi9.c 从l开始,根据加入列表的顺序为每个单词编号。当再次运行程序时,确保新的单词
fgets()参数问题。
//lianxi9.c 从l开始,根据加入列表的顺序为每个单词编号。当再次运行程序时,确保新的单词编号接着前面的编号开始。 #include <stdio.h> #include <stdlib.h> #define MAX 40 int main(void) { FILE *fp; char words[MAX]; int count = 0; if((fp = fopen("worddy","a+")) == NULL) { fprintf(stderr,"Can't open "worddy" file.\n"); exit(EXIT_FAILURE); } rewind(fp); while(fgets(words,MAX-1,fp) != NULL)count++; //这里没看懂,第二个参数有必要-1吗?fgets不是读取MAX-1个字符吗?然后在第MAX个字符加'\0' 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); while(fscanf(fp,"%s",words) == 1) puts(words); if(fclose(fp)!=0) fprintf(stderr,"Errorclosing file\n"); return 0; } [解决办法] 是没有必要,但是那样写也没有错。
引用: //lianxi9.c 从l开始,根据加入列表的顺序为每个单词编号。当再次运行程序时,确保新的单词编号接着前面的编号开始。 #include <stdio.h> #include <stdlib.h> #define MAX 40 int main(void) { FILE *fp; char words[MAX]; int count = 0; if((fp = fopen("worddy","a+")) == NULL) { fprintf(stderr,"Can't open "worddy" file.\n"); exit(EXIT_FAILURE); } rewind(fp); while(fgets(words,MAX-1,fp) != NULL)count++; //这里没看懂,第二个参数有必要-1吗?fgets不是读取MAX-1个字符吗?然后在第MAX个字符加'\0' 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); while(fscanf(fp,"%s",words) == 1) puts(words); if(fclose(fp)!=0) fprintf(stderr,"Errorclosing file\n"); return 0; } [解决办法] 安全无公害。