file-handling · intermediate · ~15 min
Streaming reads with `fgetc`; clear error semantics.
Implement long count_lines(const char *path) returning the number of newline characters in the file (so a final non-newline line is not counted), or -1 if the file can't be opened.
Counting lines in a file is the second-simplest stream-processing program (after cat). It teaches the universal pattern: read, classify, count.
#include <stdio.h>
long count_lines(const char *path) {
/* TODO */
return -1;
}
Counting newlines instead of lines (off by one if the file lacks a trailing newline). Using fgets with a too-small buffer (long lines counted twice). Forgetting to handle the last line.
Empty file (0). One line, no trailing newline (1). Trailing newline = N lines total. Binary file with embedded \n bytes — should still count.
O(file size).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.