file-handling · intermediate · ~15 min

Read the first line

Read one line and strip the newline.

Challenge

Read just the first line of a text file, with the trailing newline stripped.

Task

Implement int first_line(const char *path, char *out, int outsz) that copies the first line of the file at path into out (without the trailing '\n', NUL-terminated, bounded by outsz) and returns its length.

Input

  • path: filename of a text file the grader creates in the working directory.
  • out / outsz: destination buffer and its size.

Output

Return the length of the first line (newline excluded). Return -1 if the file can't be opened.

Example

file "fl_fixture.txt" = "hello\nworld\n"
first_line("fl_fixture.txt", out, 32)   ->   5,  out = "hello"
first_line("missing", out, 32)          ->   -1

Edge cases

  • Missing file: -1.
  • fgets keeps the newline, so strip it before measuring.

Rules

  • Read with fgets; trim a trailing '\n'; close before returning.

Input format

path: text file to read. out/outsz: result buffer and size.

Output format

int length of the first line (no newline), or -1 if the file can't be opened.

Constraints

fgets keeps the newline; strip it before returning the length.

Starter code

#include <stdio.h>
#include <string.h>

int first_line(const char *path, char *out, int outsz) {
    /* TODO */
    return -1;
}

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