Aral Code

Memory Lesson 15 of 16

C File Handling — fopen, fprintf, fscanf and fclose

Save and load data with files in C — open files with fopen modes, write with fprintf and fputs, read with fgets and fscanf, check for errors and close files.

Data in variables disappears when the program ends. Files keep it: a class list, high scores, sales records. C handles files through a FILE pointer and a set of functions from <stdio.h>.

Writing a file

#include <stdio.h>

int main(void) {
    FILE *f = fopen("grades.txt", "w");
    if (f == NULL) {
        printf("Could not open file.\n");
        return 1;
    }
    fprintf(f, "Ana %d\n", 91);
    fprintf(f, "Ben %d\n", 84);
    fprintf(f, "Carla %d\n", 95);
    fclose(f);
    printf("Saved!\n");
    return 0;
}

Output

Saved!
  • fopen(name, mode) opens a file and returns a FILE *, or NULL if it fails.
  • fprintf(f, ...) works exactly like printf, but writes to the file.
  • fclose(f) saves everything and closes the file.

File modes

ModeMeaning
"r"Read. Fails if the file doesn't exist.
"w"Write. Creates the file, or erases an existing one.
"a"Append. Adds to the end.
"r+"Read and write an existing file.
"rb", "wb"Binary versions (for raw data like images or structs).

Reading line by line

#include <stdio.h>

int main(void) {
    FILE *f = fopen("grades.txt", "r");
    if (!f) {
        printf("No saved grades yet.\n");
        return 1;
    }
    char line[100];
    int n = 1;
    while (fgets(line, sizeof line, f) != NULL) {
        printf("%d: %s", n++, line);
    }
    fclose(f);
    return 0;
}

Output

1: Ana 91
2: Ben 84
3: Carla 95

fgets returns NULL at the end of the file, which ends the loop. Each line keeps its \n, so printf doesn't add another.

Reading formatted data

#include <stdio.h>

int main(void) {
    FILE *f = fopen("grades.txt", "r");
    if (!f) return 1;
    char name[30];
    int grade, count = 0, sum = 0;
    while (fscanf(f, "%29s %d", name, &grade) == 2) {
        printf("%-6s %d %s\n", name, grade, grade >= 90 ? "*" : "");
        sum += grade;
        count++;
    }
    fclose(f);
    if (count > 0) printf("Average: %.2f\n", (double) sum / count);
    return 0;
}

Output

Ana    91 *
Ben    84 
Carla  95 *
Average: 90.00

fscanf returns how many values it read. Looping while it returns 2 stops cleanly at the end of the file or at a badly formatted line. %29s limits the name to 29 characters so it can't overflow the 30-byte array.

Appending to a log

#include <stdio.h>

int main(void) {
    FILE *log = fopen("attendance.txt", "a");
    if (!log) return 1;
    fputs("2026-12-02 Ana present\n", log);
    fclose(log);
    return 0;
}

Each run adds one line to the end, keeping earlier records.

CSV files

Write values separated by commas, and the file opens as a table in Excel or Google Sheets:

#include <stdio.h>

int main(void) {
    FILE *f = fopen("sales.csv", "w");
    if (!f) return 1;
    fprintf(f, "Item,Qty,Amount\n");
    fprintf(f, "Pandesal,10,25.00\n");
    fprintf(f, "Kape,4,32.00\n");
    fclose(f);
    printf("Open sales.csv in Excel!\n");
    return 0;
}

Output

Open sales.csv in Excel!

Where is the file?

A file name without a folder is created in the program's working directory, usually the folder you ran it from. In Code::Blocks, that's often the project folder; in VS Code, the opened folder. If you can't find your file, print a message or use a full path.

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. What does fopen return if the file can't be opened?
2. Which mode adds data without erasing the file?
3. What does fgets return at the end of the file?
4. Which function writes formatted text to a file?

By Sir Reyel · Last updated 2026-12-04