file-handling · intermediate · ~15 min
Combine fgets with substring search.
Find the first line of a text file that contains a given substring — the core of a grep-style search.
Implement int first_line_with(const char *path, const char *needle, char *out, size_t out_sz) that opens the file at path, scans it line by line, and copies the first line containing needle into out (without the trailing newline, NUL-terminated, bounded by out_sz).
path: filename of a text file the grader creates in the working directory.needle: the substring to search for.out / out_sz: destination buffer and its size.Return 0 if a matching line is found (with the line written to out, newline stripped, truncated to fit out_sz). Return -1 if no line matches or the file cannot be opened.
file "data.txt": "hello\nworld\nbye world\n"
first_line_with("data.txt", "world", out, 64) -> 0, out = "world"
first_line_with("data.txt", "missing", ...) -> -1
first_line_with("nope", "x", ...) -> -1 (file can't be opened)
out_sz.path: file to scan. needle: substring to find. out/out_sz: result buffer and size.
0 on match (matching line, newline stripped, written to out); -1 if not found or the file can't be opened.
Read with fgets; match with strstr.
#include <stdio.h>
#include <string.h>
int first_line_with(const char *path, const char *needle, char *out, size_t out_sz) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.