Skip to content

Commit 6161e99

Browse files
fixup! fixup! Fix #958: warn when feof() is used as a while loop condition
1 parent 49f0467 commit 6161e99

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

man/checkers/wrongfeofUsage.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# wrongfeofUsage
2+
3+
**Message**: Using feof() as a loop condition causes the last line to be processed twice.<br/>
4+
**Category**: Correctness<br/>
5+
**Severity**: Warning<br/>
6+
**Language**: C/C++
7+
8+
## Description
9+
10+
`feof()` returns non-zero only after a read operation has failed because the end of file was reached. When used as the sole condition of a `while` loop, the loop body executes one extra time after the last successful read: the read fails silently (or returns partial data), and only then does `feof()` return true and terminate the loop.
11+
12+
This checker warns when it finds feof in the loop condition and either:
13+
- no file-read call (e.g. `fgets`, `fread`, `fscanf`) precedes the loop and is also present inside the loop body
14+
- a control-flow statement (`return`, `break`, `goto`, `continue`, `throw`) is present in the the loop body.
15+
16+
## How to fix
17+
18+
Check the return value of the read function directly in the loop condition.
19+
20+
Before:
21+
```c
22+
void process(FILE *fp) {
23+
char line[256];
24+
while (!feof(fp)) { /* wrong: processes last line twice */
25+
fgets(line, sizeof(line), fp);
26+
puts(line);
27+
}
28+
}
29+
```
30+
31+
After:
32+
```c
33+
void process(FILE *fp) {
34+
char line[256];
35+
while (fgets(line, sizeof(line), fp) != NULL) {
36+
puts(line);
37+
}
38+
}
39+
```

0 commit comments

Comments
 (0)