file-handling · beginner · ~15 min

Buffered Word and Line Counter

Implement single-pass text stream metric analysis with word state tracking.

Challenge

Analyzing text streams efficiently requires scanning buffers without allocating intermediate strings, counting lines, words, and characters in a single pass.

Your Task

Implement:

int count_text_metrics(const char *text, size_t *lines, size_t *words, size_t *chars);

Rules

  1. If text == NULL, lines == NULL, words == NULL, or chars == NULL, return -1.
  2. Initialize *lines = 0, *words = 0, *chars = 0.
  3. If text is empty (""), leave all counts as 0 and return 0.
  4. *chars counts the total number of characters (bytes) before the NUL terminator.
  5. *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.
  6. *words counts whitespace-separated words (whitespace: ' ', '\t', '\n', '\r').
  7. Return 0 on success.

Example

size_t l, w, c;
count_text_metrics("hello world\nfoo", &l, &w, &c); // l=2, w=3, c=15

Input format

text: NUL-terminated string; lines, words, chars: output pointers.

Output format

Returns 0 on success, -1 on NULL pointer.

Constraints

Single pass. Zero dynamic allocations.

Starter code

#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;
}

Common mistakes

Missing the last line when no trailing newline exists; treating multiple spaces as multiple words.

Edge cases to handle

Empty string produces 0 lines/words/chars; text without trailing newline counts line; consecutive spaces do not increment word count.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.