The feof trap in C
feof reports that a read already failed, so testing it first reads one line too many.
#include <stdio.h>
/* Wrong: feof is only true after a read has failed. */
int overcounts(FILE *f) {
char line[128];
int n = 0;
while (!feof(f)) {
fgets(line, (int) sizeof line, f);
n++;
}
return n;
}
/* Right: the read result is the loop condition. */
int counts(FILE *f) {
char line[128];
int n = 0;
while (fgets(line, (int) sizeof line, f) != NULL) {
n++;
}
return ferror(f) ? -1 : n;
}
How it works
while (!feof(f))processes the last line twice.- The fix is to loop on the read call's own result.
ferrorafterwards distinguishes a real error from the end.
Keywords and builtins used here
FILENULLcharcountsintovercountsreturnsizeofwhile
The run, in numbers
- Lines
- 22
- Characters to type
- 391
- Tokens
- 109
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 69 seconds.
Step 3 of 4 in Opening & reading, step 3 of 12 in Files & I/O.