file-handling · intermediate · ~30 min
Walk a buffer line-by-line; call strstr per line.
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.
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.
needle, haystack — null-terminated strings.
Number of matching lines.
O(n*m) worst case is fine (strstr).
int grep_count(const char *needle, const char *haystack) { /* TODO */ return 0; }
Treating consecutive newlines as one line; missing the last line when no trailing newline; double-counting when the needle spans a newline.
Empty haystack: 0. Empty needle: every line matches.
O(haystack * needle) with naive substring search.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.