-3

fgetc() function reads characters from a text file in Ubuntu.

the last character before EoF is with code = -1.

what the heck is that? in text editor file seems ok, no strange symbols at end.

while (!feof(fp))
{
    c = fgetc(fp);
    printf("%c %i\n", c, c);//
}

1 Answers1

1

feof is meant to signal that you've tried to read past the end of file - which means that you first have to reach it. So it will only work after you try to read and the system realizes you're at the end. And what does fgetc return if you try to read past the end of file? EOF (conveniently, -1 - which is why fgetc returns an int instead of a char).

So what's happening is that you enter the loop - because you haven't yet tried to read past at the end yet - and call fgetc which returns -1 because you tried to read past the end of the file. The next time around the loop, feof tells you that you've already hit the end of the file and tried to read past it and you break out.

You should read the documentation of functions you intend to use: feof and fgetc documentation explain this. But even if they did not, a simple google search would have answered your question: Why is “while ( !feof (file) )” always wrong?.

Community
  • 1
  • 1
Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37
  • 1
    To be clear `feof` does *not* signal the end of the file. It informs that an attempt was already made to read *past* the end of a file. So it did not return `true` until after OP read the `EOF` flag, which was not part of the file content. – Weather Vane Dec 12 '15 at 22:31
  • 2
    Also explain why `c` should be defined as `int`. – chqrlie Dec 12 '15 at 22:34