Reading lines with fgets in C
fgets is the safe line reader: it takes a size and always terminates.
#include <stdio.h>
#include <string.h>
int count_lines(FILE *f) {
char line[256];
int lines = 0;
while (fgets(line, (int) sizeof line, f) != NULL) {
size_t n = strlen(line);
if (n > 0 && line[n - 1] == '\n') {
line[n - 1] = '\0';
}
lines++;
}
return lines;
}
How it works
- It keeps the newline, so strip it yourself.
- A full buffer with no newline means the line was longer.
- It returns NULL at end of file or on error.
Keywords and builtins used here
FILENULLcharcount_linesifintreturnsize_tsizeofwhile
The run, in numbers
- Lines
- 16
- Characters to type
- 260
- Tokens
- 93
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 59 seconds.
Step 2 of 4 in Opening & reading, step 2 of 12 in Files & I/O.