file-handling · intermediate · ~15 min

Count lines in a file

Streaming reads with `fgetc`; clear error semantics.

Challenge

Count the lines in a file by counting newline bytes.

Task

Implement long count_lines(const char *path) returning the number of \n characters in the file at path. No main — the grader calls it.

Input

path: the file to read.

Output

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.

Example

file "one\ntwo\nthree\n"   ->   3
empty file                  ->   0
file "no newline"           ->   0
count_lines("missing")      ->   -1

Edge cases

  • Empty file returns 0.
  • Text with no trailing newline does not count the last partial line.
  • Unopenable file returns -1.

Rules

  • Count newline bytes (do not assume a trailing newline).

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.

Input format

A file path.

Output format

The number of newline bytes as a long, or -1 if the file cannot be opened.

Constraints

Count newline bytes; do not assume a trailing newline.

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.