file-handling · intermediate · ~15 min
Streaming reads with `fgetc`; clear error semantics.
Count the lines in a file by counting newline bytes.
Implement long count_lines(const char *path) returning the number of \n characters in the file at path. No main — the grader calls it.
path: the file to read.
The count of newline bytes as a long, or -1 if the file cannot be opened. A final line with no trailing newline is therefore not counted.
file "one\ntwo\nthree\n" -> 3
empty file -> 0
file "no newline" -> 0
count_lines("missing") -> -1
0.-1.Counting lines in a file is the second-simplest stream-processing program (after cat). It teaches the universal pattern: read, classify, count.
A file path.
The number of newline bytes as a long, or -1 if the file cannot be opened.
Count newline bytes; do not assume a trailing newline.
#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.