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
- Start with No file named a.txt
- Do this Open a.txt for reading
- Result File missing
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
./lessonOpen 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.
#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;
}
No receipt yet
The program owns a fresh, empty directory, so in this run the named receipt is known to be absent.
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.
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.
What to watch for
Read errno only after fopen signals failure. This example uses a private temporary directory on macOS or Linux.