C Programming • C17 baseline, standards-specific features labeled
Read and Write Files in C
Check file-opening and read/write results, and close each successfully opened stream.
fopen returns a stream or a null pointer when the file cannot be opened. Functions such as fprintf can report write failures, and fclose can report errors that occur while buffered output is flushed. Choose text or binary mode to match the file format.
Example
#include <stdio.h>
int main(void) {
FILE *file = fopen("notes.txt", "w");
if (file == NULL) {
return 1;
}
int failed = fputs("C keeps file handling explicit.\n", file) == EOF;
if (fclose(file) == EOF) {
failed = 1;
}
return failed ? 1 : 0;
}
What to expect
The program creates or replaces notes.txt, writes one line, and reports a nonzero exit status if writing or closing fails.
Key idea: Check both the operation and the final close when write errors matter.