Always check open, read, write, and close operations; a file operation can fail after opening successfully.
Build a Complete Mental Model
C file I/O requires explicit handling of open modes, errors, partial reads or writes, buffering, text versus binary behavior, and close results. Check every FILE operation and centralize cleanup.
Apply It in Real C
Implement a text-file write and read round trip with paths for permission failure, missing file, write error, and close error.
After This Lesson
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *file = fopen("notes.txt", "w");
if (file == NULL) { perror("notes.txt"); return EXIT_FAILURE; }
int status = EXIT_SUCCESS;
if (fputs("Safe C file I/O\n", file) == EOF) {
perror("write");
status = EXIT_FAILURE;
}
if (fclose(file) == EOF) {
perror("close");
status = EXIT_FAILURE;
}
return status;
}notes.txt contains: Safe C file I/OTry It Yourself
Implement a text-file write and read round trip with paths for permission failure, missing file, write error, and close error.
Memory and Safety Warning
Using a FILE pointer without checking fopen can dereference null and invoke undefined behavior.
GNU C compiler diagnostics — GNU Project