-2
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 doesn't stop the while loop from stopping but something like !feof(in) seems to work. Any ideas?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Charana
  • 1,074
  • 1
  • 13
  • 26

1 Answers1

3

feof doesn't return EOF on end of file; it returns true, which is not equal to EOF.

fgetc will return EOF when it hits end-of-file. Your code should be written as

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); 
    }
}

You should not use feof as a loop condition, as it won't return true until after you attempt to read past the end of the file, meaning your loop will execute once too often.

John Bode
  • 119,563
  • 19
  • 122
  • 198
  • 2
    Note, though, that the loop condition in his code always happens right after a read and he doesn't use `c` unless the loop condition is true... so using `feof()` should work also. – Dmitri Nov 06 '15 at 18:10
  • Note: Subtle difference between this good solution and OP's (had it been `while(!feof(in))`). This code will quit the loop should end-of-file or input error occur. OP's code (corrected) only quits the loop on `end-of-file, – chux - Reinstate Monica Nov 06 '15 at 18:44