file-handling · beginner · ~15 min
Implement single-pass text stream metric analysis with word state tracking.
Analyzing text streams efficiently requires scanning buffers without allocating intermediate strings, counting lines, words, and characters in a single pass.
Implement:
int count_text_metrics(const char *text, size_t *lines, size_t *words, size_t *chars);
text == NULL, lines == NULL, words == NULL, or chars == NULL, return -1.*lines = 0, *words = 0, *chars = 0.text is empty (""), leave all counts as 0 and return 0.*chars counts the total number of characters (bytes) before the NUL terminator.*lines counts the number of newline characters ('\n'). If the text is non-empty and does not end in a newline, count the final line as well.*words counts whitespace-separated words (whitespace: ' ', '\t', '\n', '\r').0 on success.size_t l, w, c;
count_text_metrics("hello world\nfoo", &l, &w, &c); // l=2, w=3, c=15
text: NUL-terminated string; lines, words, chars: output pointers.
Returns 0 on success, -1 on NULL pointer.
Single pass. Zero dynamic allocations.
#include <stddef.h>
int count_text_metrics(const char *text, size_t *lines, size_t *words, size_t *chars) {
(void)text; (void)lines; (void)words; (void)chars;
return -1;
}
Missing the last line when no trailing newline exists; treating multiple spaces as multiple words.
Empty string produces 0 lines/words/chars; text without trailing newline counts line; consecutive spaces do not increment word count.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.