file-handling · intermediate · ~15 min
Read one line and strip the newline.
Read just the first line of a text file, with the trailing newline stripped.
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.
path: filename of a text file the grader creates in the working directory.out / outsz: destination buffer and its size.Return the length of the first line (newline excluded). Return -1 if the file can't be opened.
file "fl_fixture.txt" = "hello\nworld\n"
first_line("fl_fixture.txt", out, 32) -> 5, out = "hello"
first_line("missing", out, 32) -> -1
fgets keeps the newline, so strip it before measuring.fgets; trim a trailing '\n'; close before returning.path: text file to read. out/outsz: result buffer and size.
int length of the first line (no newline), or -1 if the file can't be opened.
fgets keeps the newline; strip it before returning the length.
#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.