C Notes
Complete guide to fopen() and fclose() in C — file opening modes, error checking, file paths, buffering, practical examples with output, and best practices for file management.
Before you can read from or write to a file, you must open it. And when you're done, you must close it. These two operations — fopen() and fclose() — are the bookends of every file operation in C.
fopen() — Opening a File
FILE *fopen(const char *filename, const char *mode);| Parameter | Description |
|---|---|
filename | Path to the file (relative or absolute) |
mode | How to open: "r", "w", "a", "r+", "w+", "a+", etc. |
| Returns | FILE pointer on success, NULL on failure |
Basic Usage
#include <stdio.h>
int main() {
FILE *fp;
// Open for writing (creates file if doesn't exist)
fp = fopen("output.txt", "w");
if (fp == NULL) {
printf("Error: Could not open file!\n");
return 1;
}
fprintf(fp, "File opened successfully!\n");
fprintf(fp, "Writing some data...\n");
fclose(fp);
printf("File written and closed.\n");
return 0;
}File written and closed.
Common File Modes
| Mode | Description | If file exists | If file doesn't exist |
|---|---|---|---|
"r" | Read (text) | Opens normally | Returns NULL |
"w" | Write (text) | Truncates (erases) | Creates new |
"a" | Append (text) | Writes at end | Creates new |
"r+" | Read+Write | Opens normally | Returns NULL |
"w+" | Read+Write | Truncates | Creates new |
"a+" | Read+Append | Opens for read, appends writes | Creates new |
"rb" | Read binary | Opens normally | Returns NULL |
"wb" | Write binary | Truncates | Creates new |
Error Handling — Always Check for NULL
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE *fp = fopen("nonexistent_folder/file.txt", "r");
if (fp == NULL) {
printf("Error opening file: %s\n", strerror(errno));
printf("Error code: %d\n", errno);
return 1;
}
// This code won't run if file doesn't exist
fclose(fp);
return 0;
}Error opening file: No such file or directory Error code: 2
File Paths — Relative and Absolute
// Relative paths (relative to where program runs)
FILE *f1 = fopen("data.txt", "r"); // Same directory
FILE *f2 = fopen("data/input.txt", "r"); // Subdirectory
FILE *f3 = fopen("../config.txt", "r"); // Parent directory
// Absolute paths
FILE *f4 = fopen("/home/user/data.txt", "r"); // Linux/Mac
FILE *f5 = fopen("C:\\Users\\user\\data.txt", "r"); // Windows
FILE *f6 = fopen("C:/Users/user/data.txt", "r"); // Windows (forward slash OK)fclose() — Closing a File
int fclose(FILE *stream);| Parameter | Description |
|---|---|
stream | FILE pointer to close |
| Returns | 0 on success, EOF on error |
Why Closing Matters
#include <stdio.h>
int main() {
FILE *fp = fopen("important.txt", "w");
if (fp == NULL) return 1;
fprintf(fp, "Critical data line 1\n");
fprintf(fp, "Critical data line 2\n");
// Data might still be in buffer, not on disk!
fclose(fp); // Flushes buffer to disk, releases resources
// Now data is guaranteed to be on disk
return 0;
}Opening Multiple Files
File copied successfully!
Checking if a File Exists
#include <stdio.h>
int file_exists(const char *filename) {
FILE *fp = fopen(filename, "r");
if (fp != NULL) {
fclose(fp);
return 1; // Exists
}
return 0; // Doesn't exist
}
int main() {
if (file_exists("config.txt")) {
printf("Config file found!\n");
} else {
printf("Config file not found. Creating default...\n");
FILE *fp = fopen("config.txt", "w");
if (fp) {
fprintf(fp, "# Default configuration\n");
fprintf(fp, "theme=dark\n");
fprintf(fp, "font_size=14\n");
fclose(fp);
printf("Default config created.\n");
}
}
return 0;
}Config file not found. Creating default... Default config created.
Buffering and fflush()
#include <stdio.h>
int main() {
FILE *fp = fopen("log.txt", "w");
if (fp == NULL) return 1;
fprintf(fp, "Starting process...\n");
fflush(fp); // Force write to disk NOW (not wait for buffer full)
// Long operation...
printf("Processing... (data is already on disk)\n");
fprintf(fp, "Process complete.\n");
fclose(fp); // Also flushes remaining buffer
return 0;
}Processing... (data is already on disk)
Temporary Files with tmpfile()
Read from temp: Temporary data: 42 Temp file auto-deleted.
Interview Questions
Q1: What happens if fopen() fails?
fopen() returns NULL. Common reasons: file doesn't exist (with "r" mode), permission denied, path doesn't exist, too many open files. Always check the return value before using the FILE pointer.
Q2: What's the difference between "w" and "a" modes?
"w" mode truncates (empties) the file if it exists, then writes from the beginning. "a" mode preserves existing content and appends new data at the end. Use "a" for log files, "w" for generating new output.
Q3: What does fclose() actually do internally?
fclose() flushes the output buffer (writes pending data to disk), releases the FILE structure and its buffer from memory, releases the OS file descriptor, and removes any file locks. Returns 0 on success, EOF on error.
Q4: Can you open the same file twice simultaneously?
Yes, you can open the same file with multiple FILE pointers. However, writing from multiple handles without coordination causes data corruption. Reading from multiple handles is safe.
Q5: How many files can a program have open simultaneously?
This depends on the OS. The C standard guarantees at least 8 (FOPEN_MAX). Linux typically allows 1024 per process (adjustable with ulimit). You can check FOPEN_MAX in your system.
Summary
fopen()opens a file and returns a FILE pointer (or NULL on failure)fclose()flushes buffers and releases resources- Always check if fopen returns NULL before proceeding
- Choose the right mode: "r" for read, "w" for write (truncates), "a" for append
- Use "b" suffix for binary files ("rb", "wb")
- Close every opened file to prevent data loss and resource leaks
- Use fflush() to force writes to disk without closing
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for fopen() and fclose() in C – Opening and Closing Files.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this C Programming topic.
Search Terms
c-programming, c programming, programming, file, handling, opening, and, closing
Related C Programming Topics