file-handling · intermediate · ~15 min
Iterate a text file line by line with fgets.
Count the lines in a text file by reading it one line at a time.
Implement int count_file_lines(const char *path) that returns the number of lines in the file at path, reading with fgets.
path: filename of a text file the grader creates in the working directory.
Return the number of lines, or -1 if the file can't be opened.
file "gl_fixture.txt" = "a\nb\nc\n"
count_file_lines("gl_fixture.txt") -> 3
count_file_lines("missing") -> -1
fgets returns non-NULL; use a buffer large enough for each line; close before returning.path: text file to count.
int line count, or -1 if the file can't be opened.
Loop with fgets until it returns NULL.
#include <stdio.h>
int count_file_lines(const char *path) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.