file-handling · beginner · ~20 min

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

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

Challenge

Implement void wc_counts(const char *buf, size_t n, long *lines, long *words, long *bytes):

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

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

Buffer with n bytes (may contain NULs, but tests won't).

Output format

Three counts via output pointers.

Constraints

One pass over the buffer.

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.