file-handling · beginner · ~20 min

Final Project: mini-wc — line/word/byte counter

State tracking for word boundaries; counting newlines independently of words.

Challenge

Reimplement the core of wc: count lines, words, and bytes in a memory buffer.

Task

Implement void wc_counts(const char *buf, size_t n, long *lines, long *words, long *bytes). It scans the first n bytes of buf and writes three counts through the output pointers:

  • *bytes = n.
  • *lines = number of '\n' characters.
  • *words = number of maximal runs of non-whitespace characters.

Input

  • buf: a byte buffer.
  • n: how many bytes to examine.
  • lines, words, bytes: non-NULL output pointers.

Output

Nothing returned; the three counts are written via the pointers. Treat space, tab, and newline as whitespace.

Example

wc_counts("hello world\nfoo bar baz\n", 24, ...)   ->   lines=2, words=5, bytes=24
wc_counts("   ", 3, ...)                            ->   lines=0, words=0, bytes=3
wc_counts("oneword", 7, ...)                        ->   lines=0, words=1, bytes=7

Edge cases

  • Empty buffer (n == 0): all three counts are 0.
  • All-whitespace buffer: 0 words.
  • A final word with no trailing whitespace or newline still counts.

Why this matters

wc looks trivial but the rules around what counts as a word are surprisingly nuanced. Implementing it accurately teaches careful state tracking and the difference between bytes and characters.

Input format

buf: byte buffer. n: bytes to scan. lines/words/bytes: output pointers.

Output format

Writes *bytes=n, *lines=newline count, *words=non-whitespace runs.

Constraints

One pass over the buffer; whitespace is space, tab, and newline.

Starter code

#include <stddef.h>
void wc_counts(const char *buf, size_t n, long *lines, long *words, long *bytes) { /* TODO */ }

Common mistakes

Counting whitespace runs instead of word runs; using \n as a word separator only; forgetting that the last character before EOF may close a word.

Edge cases to handle

Empty buffer. Buffer of all whitespace. Single word, no newline.

Complexity

O(n) time, O(1) memory.

Background lessons

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