ccompiler.inOnline C Compiler & Docs
C Tutorial2026-03-152 min read

Master C file handling using fopen, fclose, fprintf, fscanf, fgets, and binary operations with fread and fwrite. Complete runnable examples.

Introduction to File Handling in C

Standard C programs store data in volatile RAM, which is lost when the program terminates. File handling allows programs to persist records to secondary disk storage via file streams defined in <stdio.h>.

In C, files are manipulated using the FILE stream pointer type.

File Opening Modes

ModeDescriptionIf File ExistsIf File Missing
"r"Open for readingStarts at beginningReturns NULL
"w"Open for writingOverwrites / truncatesCreates new file
"a"Open for appendingAppends to endCreates new file
"rb" / "wb"Binary read / writeBinary streamSame as text

Writing to a Text File

Use fopen(), fprintf(), and fclose() to write structured text to disk:

c (ISO Standard)
#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");

    if (file == NULL) {
        printf("Error opening file for writing!\n");
        return 1;
    }

    fprintf(file, "C Programming File Handling\n");
    fprintf(file, "Persistent data line 2: %d\n", 42);

    fclose(file);
    printf("File written successfully!\n");
    return 0;
}

Reading from a File (fgets)

Always verify that fopen() does not return NULL before reading:

c (ISO Standard)
#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "r");
    char buffer[256];

    if (file == NULL) {
        printf("Unable to open file for reading.\n");
        return 1;
    }

    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("Read: %s", buffer);
    }

    fclose(file);
    return 0;
}

Binary File I/O (fwrite & fread)

Binary operations allow reading and writing complete memory structs directly to disk:

c (ISO Standard)
#include <stdio.h>

typedef struct {
    int id;
    double balance;
} Account;

int main() {
    Account acc = {101, 1540.50};
    FILE *file = fopen("account.bin", "wb");

    if (file != NULL) {
        fwrite(&acc, sizeof(Account), 1, file);
        fclose(file);
        printf("Account struct saved in binary format.\n");
    }

    return 0;
}

Related Tutorials & Examples