This question already has answers here:
How to use EOF to run through a text file in C?
                                
                                    (4个答案)
                                
                        
                        
                            Why is “while ( !feof (file) )” always wrong?
                                
                                    (4个答案)
                                
                        
                                4年前关闭。
            
                    
int main ()
{
    FILE *in;
    in = fopen("input.txt","r");
    char c = fgetc(in);
    while(feof(in) != EOF)
    {
    printf("%c",c);
    c = fgetc(in);
    }
}


feof(in) != EOF不会阻止while循环停止,但是类似!feof(in)的东西似乎可以工作。有任何想法吗?

最佳答案

feof在文件末尾不返回EOF;它返回true,它不等于EOF

fgetc到达文件末尾时将返回EOF。您的代码应写为

int main ()
{
    FILE *in;
    in = fopen("input.txt","r");
    int c = fgetc(in);             // note int not char
    while(c != EOF)                // compare c to EOF
    {
      printf("%c",c);
      c = fgetc(in);
    }
}


不应将feof用作循环条件,因为它只有在您尝试读取文件末尾之后才会返回true,这意味着循环将执行一次。

关于c - feof(in)!=当文件结尾时,EOF不会使while循环停止吗? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33572912/

10-10 22:22