CFile IoBeginner

fopen() / fclose()

Opens a file stream and closes it when finished.

Review the syntaxStudy the examplesOpen the coding app
FILE *f = fopen("path", "r");
if (f) fclose(f);

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Opens a file stream and closes it when finished.

The fopen() function initiates a buffered stream to a file, returning a FILE pointer that serves as an opaque handle for subsequent I/O operations like fread and fprintf. It manages internal buffers to optimize performance by batching system calls, making it generally more efficient than raw system calls for small, frequent reads or writes. However, this buffering requires a mandatory call to fclose() to ensure that any pending data is flushed from the user-space buffer to the kernel and that the associated file descriptor and heap memory are released. In multi-threaded environments, access to the stream is usually thread-safe at the function level, but developers must be wary of 'r+' vs 'w+' modes: 'w' truncates an existing file to zero length immediately, whereas 'a' forces all writes to the end of the file regardless of the seek position. On non-POSIX systems like Windows, appending 'b' (e.g., 'rb' or 'wb') is critical to prevent the runtime from translating newline characters ( ) into carriage-return/line-feed sequences.

Quick reference

Syntax

FILE *f = fopen("path", "r");
if (f) fclose(f);

Inputs

Parameters

pathconst char* · File path to open.
modeconst char* · Open mode: "r", "w", "a", "rb", "wb", etc.

See it in practice

Examples

1

Safely Writing to a New File

#include <stdio.h>

int main() {
    FILE *f = fopen("output.txt", "w");
    if (f == NULL) {
        perror("Error opening file");
        return 1;
    }
    fprintf(f, "Hello, System Programming!\n");
    fclose(f);
    return 0;
}
Output:
(Creates or overwrites output.txt with the provided string)

Uses 'w' mode to create a file. Crucially checks for NULL before using the file pointer to prevent a segmentation fault.

2

Reading a File Line by Line

#include <stdio.h>

int main() {
    char buffer[256];
    FILE *f = fopen("data.csv", "r");
    if (!f) return 1;

    while (fgets(buffer, sizeof(buffer), f)) {
        printf("Row: %s", buffer);
    }

    fclose(f);
    return 0;
}
Output:
Row: [contents of first line] Row: [contents of second line]...

Demonstrates 'r' mode for reading. fgets stops reading at the newline or buffer limit, making it safer than gets().

3

Appending Data Without Overwriting

#include <stdio.h>

void log_message(const char *msg) {
    FILE *log = fopen("app.log", "a");
    if (log) {
        fprintf(log, "LOG: %s\n", msg);
        fclose(log);
    }
}
Output:
(Appends a new line to app.log every time the function is called)

The 'a' mode (append) ensures that the file pointer is moved to the end of the file before every write operation.

Debug faster

Common Errors

1

LogicError

Cause: Failing to check for a NULL return value from fopen, leading to a crash when passing the invalid pointer to fprintf or fgets.

Fix: Implement an 'if (fptr == NULL)' check immediately after the fopen call.

FILE *f = fopen("missing.txt", "r");
fgets(buf, 10, f); // CRASH if file does not exist
2

ResourceLeak

Cause: Opening files inside a loop or function and forgetting to call fclose, eventually hitting the system's maximum file descriptor limit (EMFILE).

Fix: Ensure every execution path (including error returns) calls fclose() on an open FILE pointer.

for(int i=0; i<10000; i++) {
  FILE *f = fopen("log.txt", "r");
  // Forgot fclose(f)
}

Runtime support

Compatibility

C89+

stdio.h; mode strings vary slightly across platforms

Source: MDN Web Docs

Common questions

Frequently Asked Questions

Opens a file stream and closes it when finished.

path: File path to open. mode: Open mode: "r", "w", "a", "rb", "wb", etc.

LogicError: Implement an 'if (fptr == NULL)' check immediately after the fopen call. ResourceLeak: Ensure every execution path (including error returns) calls fclose() on an open FILE pointer.