file-handling · intermediate · ~15 min

First line containing a substring

Combine fgets with substring search.

Challenge

Find the first line of a text file that contains a given substring — the core of a grep-style search.

Task

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).

Input

  • 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.

Output

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.

Example

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)

Edge cases

  • File cannot be opened: return -1.
  • No line contains the needle: return -1.
  • Strip the trailing newline before copying; keep the result within out_sz.

Input format

path: file to scan. needle: substring to find. out/out_sz: result buffer and size.

Output format

0 on match (matching line, newline stripped, written to out); -1 if not found or the file can't be opened.

Constraints

Read with fgets; match with strstr.

Starter code

#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.