File Handling in C

File Handling in C — conceptual cover illustration
File Handling in C — conceptual cover illustration

File handling connects C programs to persistent storage. Learn how to open, read, write, and close files using standard streams, fopen, fprintf, and fscanf in C.

File handling in C connects programs to persistent secondary storage (hard drives, SSDs). Using standard streams (<stdio.h>), programs can create, read, write, and append structured and unstructured data.

Files are accessed through an opaque FILE pointer returned by fopen(). The open mode ('r' for read, 'w' for write/truncate, 'a' for append) dictates how the operating system file descriptor is configured.

Always check whether fopen() returns NULL before reading or writing; attempting to operate on a NULL FILE pointer triggers a fatal segmentation fault. Always close opened files with fclose() to flush write buffers to disk.

Interactive Runnable C Implementation

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *filepath = "/tmp/demo_output.txt";
    FILE *fout = fopen(filepath, "w");
    if (fout == NULL) {
        perror("Error opening file for writing");
        return EXIT_FAILURE;
    }
    fprintf(fout, "Hello from the online C compiler file sandbox!\nLine 2: Ephemeral file storage.\n");
    fclose(fout);
    FILE *fin = fopen(filepath, "r");
    if (fin == NULL) {
        perror("Error opening file for reading");
        return EXIT_FAILURE;
    }
    char buffer[256];
    printf("--- File Content Readout ---\n");
    while (fgets(buffer, sizeof(buffer), fin) != NULL) {
        printf("%s", buffer);
    }
    fclose(fin);
    return EXIT_SUCCESS;
}

Open example in compiler

Expected Output

--- File Content Readout ---
Hello from the online C compiler file sandbox!
Line 2: Ephemeral file storage.

Frequently Asked Questions

Why does fopen return NULL when writing to a local file in an online compiler?

Web sandboxes mount the root application filesystem as read-only for security. Only the /tmp/ directory is writable by user execution processes.

What is the difference between text mode and binary mode in fopen?

On POSIX systems there is no difference, but on Windows, text mode ("r", "w") translates "\n" to "\r\n", while binary mode ("rb", "wb") preserves raw exact bytes.

Related examples