Library contents

C fopen and ENOENT

On a POSIX system, fopen returns a null pointer on failure and errno identifies a missing path.

A simple example

fopen and ENOENT

  1. Start with No file named a.txt
  2. Do this Open a.txt for reading
  3. Result File missing
The missing-path outcome lets the caller offer an empty starting state or ask for another name.

Syntax

C syntax
errno == ENOENT
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

Open the first receipt of the day

A new checkout starts with an empty receipt folder. When the cashier asks to reprint today's first receipt, the app should explain that a receipt has yet to be saved.

From the programchar folder[] = "/tmp/checkout-XXXXXX"
ResultNo receipt yet
lesson.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

int main(void) {
    char folder[] = "/tmp/checkout-XXXXXX";
    if (mkdtemp(folder) == NULL) return 1;
    char receipt[sizeof folder + sizeof "/today.txt"];
    snprintf(receipt, sizeof receipt, "%s/today.txt", folder);
    FILE *input = fopen(receipt, "r");
    int missing = input == NULL && errno == ENOENT;
    if (input) fclose(input);
    if (rmdir(folder) != 0) return 1;
    if (missing) puts("No receipt yet");
    return 0;
}
Output
No receipt yet

The program owns a fresh, empty directory, so in this run the named receipt is known to be absent.

Advertisements

Read a saved shift record

The closing clerk saved the file before leaving. Open the expected file and show the desk whether it is available.

Givenrecord.txt exists
Worked resultFile available

Handle an unsubmitted handover

The next shift opens an empty inbox before the first clerk submits a file. Open the expected file and show the desk whether it is available.

Givenrecord.txt missing
Worked resultAsk for the file

What to watch for

Read errno only after fopen signals failure. This example uses a private temporary directory on macOS or Linux.

Documentation for fopen and ENOENT