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 consistent FILE* stream API.

⚙️ How It Works: Access Modes Overview

Mode String Access Action Behavior If File Exists Behavior If File Does NOT Exist
"r"Read TextOpens for reading at beginningFails (returns NULL)
"w"Write TextTruncates (erases) file to 0 bytes!Creates new empty file
"a"Append TextAppends writes to end of fileCreates new empty file
"r+"Read / Write TextOpens for update without erasingFails (returns NULL)
"w+"Read / Write TextTruncates (erases) file to 0 bytes!Creates new empty file
"a+"Read / Append TextOpens for reading/appendingCreates new empty file
"rb", "wb"Binary StreamBinary byte-for-byte stream I/OSame 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 for output.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(): Calling fputs() or fscanf() on a NULL file 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() in char instead of int: EOF is an integer constant (typically -1). Storing fgetc() in a char variable breaks EOF detection on platforms where char is unsigned!

📌 Important Rules & Limitations

  • Always verify if (fp != NULL) after every fopen() call.
  • Always close open streams using fclose(fp) to avoid running out of OS file handles.
  • Store fgetc() return values in an int variable to compare with EOF correctly.

🌐 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

  1. What is the difference between file mode "w" and file mode "a"?
  2. Why must the return value of fgetc() be assigned to an int variable rather than a char variable?
  3. 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.

🧭 Navigation & Breadcrumbs

← Module 16 Guide | Next: 02. Formatted Text I/O →