fopen, fclose & File Modes
`fopen` opens a file and returns a `FILE*` pointer, or `NULL` on failure. **Always check for NULL.** `fclose` flushes the buffer and releases the file descriptor. Forgetting `fclose` causes data loss (for writes) and resource leaks. Understanding the file modes (`r`, `w`, `a`, `rb`, `wb`, etc.) prevents data corruption.
11 min•By Priygop Team•Updated 2026
fopen Modes & Resource Management Patterns
fopen Modes & Resource Management Patterns
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(void) {
/* ── fopen modes ──────────────────────────────────────
"r" — read text; error if file doesn't exist
"w" — write text; CREATES or TRUNCATES file
"a" — append text; creates if needed, adds at end
"r+" — read+write; error if doesn't exist
"w+" — read+write; creates or truncates
"rb" — read binary (important on Windows:
vs
)
"wb" — write binary
"ab" — append binary */
/* ── Write a text file ───────────────────────────────── */
FILE *fp = fopen("test.txt", "w");
if (fp == NULL) {
fprintf(stderr, "fopen failed: %s
", strerror(errno));
return 1;
}
fprintf(fp, "Line 1
");
fprintf(fp, "Value: %d
", 42);
fprintf(fp, "Pi: %.4f
", 3.14159);
if (fclose(fp) != 0) { /* fclose can fail — always check! */
fprintf(stderr, "fclose failed: %s
", strerror(errno));
return 1;
}
printf("Wrote test.txt
");
/* ── Read it back ────────────────────────────────────── */
fp = fopen("test.txt", "r");
if (fp == NULL) {
perror("fopen test.txt for reading"); /* perror uses errno */
return 1;
}
char line[256];
int lineno = 0;
while (fgets(line, sizeof(line), fp) != NULL) {
/* fgets reads up to sizeof(line)-1 chars + null terminates
Includes the '
' at end of line (if it fits) */
line[strcspn(line, "
")] = '