file-handling · beginner · ~15 min
Streaming character classification without I/O.
Count the lines in text you have already loaded into memory, by tallying newline characters.
Implement size_t buffer_line_count(const char *buf) that returns how many '\n' characters appear in the NUL-terminated string buf.
buf — a NUL-terminated C string (the in-memory contents of a file). It may be empty.
The number of '\n' bytes in buf, as a size_t.
"a\nb\nc\n" -> 3
"a\nb" -> 1
"" -> 0
'\n' bytes are tallied).buf: a NUL-terminated string holding file contents (may be empty).
size_t count of '\n' characters in buf.
Count newline bytes only; do no I/O.
#include <stddef.h>
size_t buffer_line_count(const char *buf) { /* TODO */ return 0; }
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.