Library contents

C fgets and ferror

fgets reads at most one less than the buffer size and retains a newline when it fits. Its null return can mean end of input or a read error.

A simple example

fgets and ferror

  1. Start with Two lines, A then B
  2. Do this Read one line at a time
  3. Result Two records
The line reader allows the first line to be processed before the second.

Syntax

C syntax
fgets(buffer, sizeof buffer, stream)
Run this example in C

Save the program as lesson.c. Use C17 and a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Count records in a temporary stream

A job needs scratch storage while preparing its final report. Use a temporary stream or file to stage the records, then close it once the contents have been counted or passed onward.

From the programsize_t count = 0
Result2 records
lesson.c
#include <stdio.h>

int main(void) {
    FILE *stream = tmpfile();
    if (!stream) return 1;
    if (fputs("north\nsouth", stream) == EOF || fseek(stream, 0, SEEK_SET) != 0) {
        fclose(stream);
        return 1;
    }
    char line[32];
    size_t count = 0;
    while (fgets(line, sizeof line, stream)) ++count;
    int failed = ferror(stream);
    if (fclose(stream) == EOF || failed) return 1;
    printf("%zu records\n", count);
    return 0;
}
Output
2 records

The final record here ends at EOF without a newline and still counts. Longer records require assembling multiple chunks. The count below is valid for these known short lines.

Open Group function reference for fgets and ferror

Advertisements

Read a studio sign-in sheet

A rehearsal has two names with a reserved blank row between them. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenAda / blank / Kim
Worked result3

Read a single shift instruction

A shop closes after recording one instruction without a final newline. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenLock door + EOF
Worked result1