Example 1 — Handle a missing file and a successful open
The first open fails; the second creates a new file.
#include <stdio.h>
int main(void) {
FILE *fp = fopen("missing_file_123.txt", "r");
if (fp == NULL) {
printf("could not open missing_file_123.txt\n");
} else {
fclose(fp);
}
fp = fopen("out.txt", "w");
if (fp == NULL) return 1;
fputs("data\n", fp);
if (fclose(fp) == 0) printf("closed ok\n");
return 0;
} How It Works
- Reading a file that does not exist returns
NULL. - Opening with
"w"creates the file. fclosereturning0means the data was flushed successfully.
