file-handling · intermediate · ~15 min

First line containing a substring

Combine fgets with substring search.

Challenge

Implement int first_line_with(const char *path, const char *needle, char *out, size_t out_sz) that reads path line by line and writes the first line containing needle into out (without the trailing newline). Return 0 on success, -1 if not found or file can't be opened.

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.