cfilepointersfgetcfeof

Confusion with == EOF vs feof


I opened a file, the stream is found at the address of pointer ptr. I am attempting to see whether or not a file is blank. Using the following

if (fgetc(ptr) != EOF)

works as expected. When the file is empty, the statement is not executed. When the file is not empty, the statement is executed.

However, using

if (!feof(ptr))

always executes the statement.

Why does this happen? Is there a way to use the feof function?


Solution

  • Is there a way to use the feof function?

    Yes, there is. After an input function has returned a value that indicates that it has no more input to process, you can call feof() and/or ferror() to determine whether the condition was caused by reaching the end of the input or some error condition.

    This is the only valid use for the feof() and ferror() functions.

    The result that indicates that no more input remains differs from one function to another. For example fgetc() returns the value EOF, fgets() returns a null pointer, and fread() returns some value less than the number of records requested. You need to read the documentation for each input function to see how it works.