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 blank, the statement is not executed. When the file is not blank, the statement is not executed.
However, using
if (!feof(ptr))
always executes the statement.
Why does this happen? Is there a way to use the feof
function?
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 fgets()
returns the value EOF
, while 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.