01. File Streams, fopen(), fclose() & Access Modes
🟢 Difficulty: Beginner | FILE* Pointers, Stream Handles, File Modes & NULL Validation
📖 Definition
In C, a file stream is represented by an opaque pointer to a FILE structure handle declared in <stdio.h>. The fopen() function opens a disk file path with a specified access mode (such as read, write, or append), returning a FILE* pointer. The fclose() function flushes stream buffers and releases OS file descriptors.
🎯 Why It Is Used
- Data Persistence: Preserving application state, configuration settings, and database records across system reboots.
- Stream Abstraction: Unifying file I/O, console input (
stdin), console output (stdout), and error logging (stderr) under a single consistentFILE*stream API.
⚙️ How It Works: Access Modes Overview
| Mode String | Access Action | Behavior If File Exists | Behavior If File Does NOT Exist |
|---|---|---|---|
"r" | Read Text | Opens for reading at beginning | Fails (returns NULL) |
"w" | Write Text | Truncates (erases) file to 0 bytes! | Creates new empty file |
"a" | Append Text | Appends writes to end of file | Creates new empty file |
"r+" | Read / Write Text | Opens for update without erasing | Fails (returns NULL) |
"w+" | Read / Write Text | Truncates (erases) file to 0 bytes! | Creates new empty file |
"a+" | Read / Append Text | Opens for reading/appending | Creates new empty file |
"rb", "wb" | Binary Stream | Binary byte-for-byte stream I/O | Same rules as text counterparts |
📝 Syntax
#include <stdio.h>
FILE *file_ptr = fopen("config.txt", "r");
if (file_ptr == NULL) {
perror("Error opening file"); // Prints OS error message (e.g., "File not found")
return 1;
}
// Perform file operations...
fclose(file_ptr); // Mandatory cleanup!
file_ptr = NULL;
🔀 Standard Stream Pre-defined Handles
C automatically opens three standard stream handles on startup:
stdin: Standard Input Stream (Keyboard input)stdout: Standard Output Stream (Terminal screen)stderr: Standard Error Stream (Unbuffered terminal error output)
🌱 Beginner Example: Opening, Writing & Closing a File
#include <stdio.h>
int main(void) {
FILE *fp = fopen("output.txt", "w"); // Create or truncate file
if (fp == NULL) {
perror("Failed to open output.txt");
return 1;
}
fputs("Hello, C File Handling!\n", fp);
printf("Successfully wrote message to output.txt\n");
fclose(fp); // Flushes buffer to disk and closes stream
return 0;
}
🌼 Intermediate Example: Reading File Character-by-Character
#include <stdio.h>
int main(void) {
FILE *fp = fopen("output.txt", "r");
if (fp == NULL) {
perror("Could not open output.txt for reading");
return 1;
}
int ch; // Must use 'int' to capture EOF properly!
printf("=== File Contents ===\n");
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
return 0;
}
🌲 Advanced Example: Safe File Appender with Error Handling
#include <stdio.h>
#include <stdbool.h>
bool append_log_entry(const char *filename, const char *log_message) {
if (filename == NULL || log_message == NULL) return false;
FILE *log_file = fopen(filename, "a"); // Append mode
if (log_file == NULL) {
perror("Error opening log file");
return false;
}
if (fputs(log_message, log_file) == EOF || fputs("\n", log_file) == EOF) {
perror("Error writing to log file");
fclose(log_file);
return false;
}
fclose(log_file); // Guarantees log write is committed
return true;
}
int main(void) {
if (append_log_entry("app.log", "[INFO] System Boot Event 0x101")) {
printf("Log entry appended successfully.\n");
}
return 0;
}
🔍 Line-by-Line Explanation
FILE *fp = fopen("output.txt", "w");: Requests a write handle foroutput.txt.if (fp == NULL) perror(...): Mandatory check verifying file opened successfully before attempting stream calls.while ((ch = fgetc(fp)) != EOF): Reads character stream until reaching End-Of-File (EOF).fclose(fp);: Commits unwritten kernel buffer data to physical storage media.
💻 Expected Terminal Output
Successfully wrote message to output.txt
=== File Contents ===
Hello, C File Handling!
Log entry appended successfully.
⚠️ Common Mistakes & Pitfalls
- Forgetting NULL Check on
fopen(): Callingfputs()orfscanf()on aNULLfile pointer causes an immediate Segmentation Fault crash. - Accidentally Overwriting Files with Mode
"w": Opening an existing file with mode"w"instantly truncates it to 0 bytes! Use mode"a"to append data safely. - Capturing
fgetc()incharinstead ofint:EOFis an integer constant (typically-1). Storingfgetc()in acharvariable breaksEOFdetection on platforms wherecharis unsigned!
📌 Important Rules & Limitations
- Always verify
if (fp != NULL)after everyfopen()call. - Always close open streams using
fclose(fp)to avoid running out of OS file handles. - Store
fgetc()return values in anintvariable to compare withEOFcorrectly.
🌐 Multilingual Explanation: English
File handling uses FILE* stream pointers. Always check if fopen() returns NULL, use mode "a" to append without erasing, and close streams with fclose().
🌐 Multilingual Explanation: Hindi (Roman Script)
File handling ke liye FILE* pointer ka upyog hota hai. fopen() ke baad NULL check zaroori hai. Purana data erse na karne ke liye mode "a" (append) ka use karein.
🌐 Multilingual Explanation: Marathi (Roman Script)
File operations sathi FILE* stream pointer vapartat. fopen() nantar NULL check kara aani nehamhi fclose() ne stream close kara.
❓ Practice Questions
- What is the difference between file mode
"w"and file mode"a"? - Why must the return value of
fgetc()be assigned to anintvariable rather than acharvariable? - What happens if you forget to call
fclose()on a file opened for writing?
🚀 Practical Coding Challenge
Write a C program named line_counter.c that opens a text file specified by the user, reads it character-by-character, and counts the total number of newline characters ('\n') to output total line count.