file-handling · intermediate · ~30 min

Final Project: mini-grep — substring match in lines

Walk a buffer line-by-line; call strstr per line.

Challenge

Implement int grep_count(const char *needle, const char *haystack) that returns the number of lines in haystack that contain needle as a substring. Lines are separated by \n. The final line may be unterminated.

Why this matters

grep is the second-most-used UNIX tool after ls. Implementing a no-regex 'fixed string' variant teaches buffer scanning and line iteration without needing the full regex engine.

Input format

needle, haystack — null-terminated strings.

Output format

Number of matching lines.

Constraints

O(n*m) worst case is fine (strstr).

Starter code

int grep_count(const char *needle, const char *haystack) { /* TODO */ return 0; }

Common mistakes

Treating consecutive newlines as one line; missing the last line when no trailing newline; double-counting when the needle spans a newline.

Edge cases to handle

Empty haystack: 0. Empty needle: every line matches.

Complexity

O(haystack * needle) with naive substring search.

Background lessons

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