"consuming it up" 后无法使用 fgets() 读取文件?

Cannot use fgets() to read file after "consuming it up"?

调试了一段时间的程序,发现C:

中的fgets()函数有问题

示例代码:

....
char arr[50];
File* file=fopen("mytext.txt","r");

for(int i=0;i<=100;++i){
    ....
    fgets(arr,sizeof(arr),file);        //I use a for loop here for example 
    ....                                //just to illustrate that I use the 
    ...do some stuff...                 //fgets() function lots of times
   }

 fgets(arr,sizeof(arr),file);           //And now I use it again but get nothing
                                        //because I have used the fgets() to consume the file up
 ....

所以你看,我想在这里说的是:当你使用fgets()从文件中获取数据的次数太多时,它会到达文件的末尾。然后当你再次使用它时,它不会 return 什么(只是一个空指针但没有错误!!)

我调试了一段时间后发现了这个问题。而且我注意到其他格式输入函数也存在相同的问题,例如 scanf().

所以我想知道是否有一种方法可以刷新机器并进行更新,以便我可以再次使用 fgets() 函数。 谢谢

您使用的是文件指针,fgets() 保持 运行 直到到达 EOF。所以当没有什么可读的时候returns NULL表示EOF。 因此,为了到达文件的开头,您需要使用

rewind(file);

并使用 fgets() 再次读取问题不在于 fgets(),因为您理解文件访问期间文件指针不断移动。