file-handling · beginner · ~20 min
State tracking for word boundaries; counting newlines independently of words.
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.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.
Buffer with n bytes (may contain NULs, but tests won't).
Three counts via output pointers.
One pass over the buffer.
#include <stddef.h>
void wc_counts(const char *buf, size_t n, long *lines, long *words, long *bytes) { /* TODO */ }
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.
Empty buffer. Buffer of all whitespace. Single word, no newline.
O(n) time, O(1) memory.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.