请问rewind()的有关问题
请教rewind()的问题本帖最后由 nain001 于 2013-03-20 13:06:31 编辑书中文件IO例子,创建一个文件,向文件
请教rewind()的问题
本帖最后由 nain001 于 2013-03-20 13:06:31 编辑 书中文件IO例子,创建一个文件,向文件中写入内容,并按单词顺序显示出来。
#include<stdio.h>
#include<stdlib.h>
#define MAX 40
int main(void){
FILE * fp;
char words[MAX];
if((fp=fopen("words","a+"))==NULL){
fprintf(stderr,"Can't open "words" \n");
exit(1);
}
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,"%s ",words);
puts("File contents: ");
rewind(fp);/*回到文件的开始处*/
while(fscanf(fp,"%s",words)==1);
puts(words);
if(fclose(fp)!=0)
fprintf(stderr,"Error in closing file.\n");
return 0;
}
运行之后:
Enter words to add to the file: press the Enter
key at the beginning of a line to terminate.
are you my friend?[enter]
[enter]File contents:
friend?
为什么是这种情况,不是rewind回到文件头么,书中的例子是显示:
are
you
my
friend?
求解?
[解决办法]while(fscanf(fp,"%s",words)==1);这句你为什么要加个";"号呢,
就导致了不能循环打印。
楼主结贴吧。
[解决办法]不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//...
if (条件2) continue;
//...
if (条件3) return;
//...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
whlie (!feof(f)) {
a=fgetc(f);
//...
b=fgetc(f);//可能此时已经feof了!
//...
}
而这样写就没有问题:
whlie (1) {
a=fgetc(f);
if (feof(f)) break;
//...
b=fgetc(f);
if (feof(f)) break;
//...
}
类似的例子还可以举很多。