Library contents

C fgets

Open a small text note and read back its contents.

A simple example

fgets

  1. Start with A file containing A
  2. Do this Read it as text
  3. Result "A"
Decoding the single ASCII byte yields the letter A.

Syntax

C syntax
fgets(note, sizeof note, file)
Run these examples in C

Save one example at a time as lesson.c. Use C17 on macOS or Linux with a POSIX shell.

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

Read a saved shopping note

A small application saves a human-readable note for the next time it opens. Choose the text encoding and read or write the file deliberately so the saved characters can be recovered as intended.

Resultmilk
lesson.c
#include <stdio.h>

int main(void) {
    FILE *file = tmpfile();
    if (!file) return 1;
    if (fputs("milk", file) == EOF) { fclose(file); return 1; }
    rewind(file);
    char note[16];
    if (!fgets(note, sizeof note, file)) { fclose(file); return 1; }
    puts(note);
    fclose(file);
    return 0;
}
Output
milk

The buffer has space for the four letters and the string terminator. A longer line can require several reads.

Advertisements

Prepare a gallery label

A curator stores a short UTF-8 caption beside an exhibit. Save the note and read it back before the desk closes. Which characters are recovered?

GivenFile contents “clay”
Worked resultclay

Prepare a studio handover

A stage manager saves a two-word instruction for the next shift. Save the note and read it back before the desk closes. Which characters are recovered?

GivenFile contents “ring bell”
Worked resultring bell

What to watch for

Use an explicit text encoding for shared data. A large file is usually better read in smaller pieces.

Documentation for fgets