-1

Having simple text file like myfile1.txt:

cat myfile1.txt:

abc

and below code

# include <stdio.h>
# include <string.h>
# include <errno.h>
# include <unistd.h>


char mybuffer[80] = "abc\n";
char* result = NULL;

int main() {
        FILE* pFile;
        pFile = fopen ("myfile1.txt", "r+");
        int c;

        if (pFile == NULL)
                perror ("Error opening file");
        else {
                result = fgets(mybuffer, 80, pFile);

                if (feof(pFile)) {
                        printf("fgets EOF");
                }

                fclose (pFile);
                return 0;
        }
}

Why doesn't the function feof returns nonzero while the end of the stream has been reached (fgets gets 3 chars "abc" and hits EOF)?

Daros
  • 59
  • 5
  • Because that's not how `feof` works. `feof` does not return true when reaching the end of the stream; it returns true after trying to read from the stream *after* it's already at the end. https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong – jamesdlin Jun 17 '19 at 16:05
  • @jamesdlin But wait, after calling `fgets` like above isn't the stream indead at the end? – Daros Jun 18 '19 at 15:44
  • After the `fgets` call above, the stream will be *at* the end, but `fgets` did not try to read *past* the end. – jamesdlin Jun 18 '19 at 17:29

1 Answers1

1

Because feof() does not return true until an attempt to read past the end of the file.

Per the documentation:

Checks whether the end-of-File indicator associated with stream is set, returning a value different from zero if it is.

This indicator is generally set by a previous operation on the stream that attempted to read at or past the end-of-file.

Community
  • 1
  • 1
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466