typestar

Reading lines with fgets in C

fgets is the safe line reader: it takes a size and always terminates.

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

int count_lines(FILE *f) {
    char line[256];
    int lines = 0;

    while (fgets(line, (int) sizeof line, f) != NULL) {
        size_t n = strlen(line);
        if (n > 0 && line[n - 1] == '\n') {
            line[n - 1] = '\0';
        }
        lines++;
    }
    return lines;
}

How it works

  1. It keeps the newline, so strip it yourself.
  2. A full buffer with no newline means the line was longer.
  3. It returns NULL at end of file or on error.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
260
Tokens
93
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 2 of 4 in Opening & reading, step 2 of 12 in Files & I/O.

← Previous Next →