My professor write a C code about fgets,feof with using stdin. But I don't understand how it works.
fgets(list, 100, stdin);
while (!feof(stdin))
{
printf("feof!");
fgets(list, 100, stdin);
}
when i write a 'hello', function while is working. why feof(stdin) returns 0?
I think first fgets read stdin buffer all of string(include '\0'). therefore I think while shouldn't work because feof(stdin) returns 1 What am i wrong?
Tip: always check the return value of input functions and most other I/O functions too.
Yes, calling
printf("feof!");
inside the loop is misleading as the end-of-file indicator forstdin
is not set given the prior test conditionwhile (!feof(stdin))
.Do not use
feof()
for this task for primary detectionfgets()
returnsNULL
when:An end-of-file just occurred in the previous input operation.
An end-of-file had occurred in the some input operations even before that.
An input error just occurred. Examples: file to read is an output stream or a parity error on some serial communication.
while (!feof(stdin))
only detects 1 & 2.Unless the return value of
fgets(list, 100, stdin)
is checked, usinglist
may be a problem.feof()
is useful after an I/O function returned the possibility of the need.Size to the object, avoid magic numbers
Good usage: