file-handling · intermediate · ~30 min
Walk a buffer line-by-line; call strstr per line.
Count how many lines of in-memory text contain a given substring — the heart of a fixed-string grep.
Implement int grep_count(const char *needle, const char *haystack) that returns the number of lines in haystack that contain needle as a substring.
needle: the substring to look for (NUL-terminated).haystack: NUL-terminated text whose lines are separated by '\n'. The final line may be unterminated.The count of matching lines, as an int.
grep_count("foo", "foo\nbar\nfoobar\n") -> 2
grep_count("xyz", "aaa\nbbb") -> 0
grep_count("end", "just one end") -> 1
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: substring to find. haystack: NUL-terminated text, lines split by '\n'.
int — number of lines containing needle.
O(haystack * needle) substring search is fine.
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.