file-handling · intermediate · ~15 min

Count lines in a file

Streaming reads with `fgetc`; clear error semantics.

Challenge

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.

Why this matters

Counting lines in a file is the second-simplest stream-processing program (after cat). It teaches the universal pattern: read, classify, count.

Starter code

#include <stdio.h>

long count_lines(const char *path) {
    /* TODO */
    return -1;
}

Common mistakes

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.

Edge cases to handle

Empty file (0). One line, no trailing newline (1). Trailing newline = N lines total. Binary file with embedded \n bytes — should still count.

Complexity

O(file size).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.