file-handling · beginner · ~20 min
State tracking for word boundaries; counting newlines independently of words.
Reimplement the core of wc: count lines, words, and bytes in a memory buffer.
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.buf: a byte buffer.n: how many bytes to examine.lines, words, bytes: non-NULL output pointers.Nothing returned; the three counts are written via the pointers. Treat space, tab, and newline as whitespace.
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
n == 0): all three counts are 0.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.
buf: byte buffer. n: bytes to scan. lines/words/bytes: output pointers.
Writes *bytes=n, *lines=newline count, *words=non-whitespace runs.
One pass over the buffer; whitespace is space, tab, and newline.
#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.