file-handling · intermediate · ~15 min

Count lines in a file

Iterate a text file line by line with fgets.

Challenge

Count the lines in a text file by reading it one line at a time.

Task

Implement int count_file_lines(const char *path) that returns the number of lines in the file at path, reading with fgets.

Input

path: filename of a text file the grader creates in the working directory.

Output

Return the number of lines, or -1 if the file can't be opened.

Example

file "gl_fixture.txt" = "a\nb\nc\n"
count_file_lines("gl_fixture.txt")   ->   3
count_file_lines("missing")          ->   -1

Edge cases

  • Missing file: -1.

Rules

  • Loop while fgets returns non-NULL; use a buffer large enough for each line; close before returning.

Input format

path: text file to count.

Output format

int line count, or -1 if the file can't be opened.

Constraints

Loop with fgets until it returns NULL.

Starter code

#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.