Tip: always check the return value of input functions and most other I/O functions too.
fgets(list, 100, stdin); // Weak code
Yes, calling printf("feof!");
inside the loop is misleading as the end-of-file indicator for stdin
is not set given the prior test condition while (!feof(stdin))
.
How to read from stdin with fgets()?
Do not use feof()
for this task for primary detection
fgets()
returns NULL
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, using list
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:
char list[100];
while (fgets(list, sizeof list, stdin)) {
printf("%s", list):
}
if (feof(stdin)) {
puts("End-of-file");
} else if (ferror(stdin)) {
puts("Error");
} else {
puts("Unexpected state");
}