file-handling · intermediate · ~15 min

First error line number

Track a line counter while scanning.

Challenge

Find where the first error appears in a log, reported as a line number.

Task

Implement int first_error_line(const char *log) that returns the 1-based line number of the first line containing "ERROR".

Input

log: a multi-line string, lines separated by '\n'.

Output

Return the 1-based line number of the first line containing "ERROR", or -1 if no line does.

Example

first_error_line("a\nb ERROR\nc\n")   ->   2
first_error_line("ERROR here\n")        ->   1
first_error_line("all good\n")          ->   -1

Edge cases

  • No line contains "ERROR": -1.
  • Line numbering starts at 1.

Input format

log: multi-line string (lines split by '\n').

Output format

int 1-based line number of the first "ERROR" line, or -1 if none.

Constraints

Count lines from 1; match "ERROR" within a single line.

Starter code

#include <string.h>

int first_error_line(const char *log) {
    /* TODO */
    return -1;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.