Reading and Writing Files

Variables disappear when a program ends. To keep data, save it in a file. The steps are always the same:

StepFunction
1. Open the fileFILE *f = fopen("name.txt", "w");
2. Write or readfprintf, fgets, fscanf
3. Close itfclose(f);

The second part of fopen is the mode:

ModeMeaning
"r"Read an existing file
"w"Write a new file (an old file with the same name is wiped!)
"a"Append: add to the end of the file

Writing and reading back

#include <stdio.h>

int main() {
    FILE *f = fopen("scores.txt", "w");
    if (f == NULL) {
        printf("Could not open the file\n");
        return 1;
    }
    fprintf(f, "Asha 90\n");
    fprintf(f, "Ben 75\n");
    fclose(f);

    char name[20];
    int score;
    f = fopen("scores.txt", "r");
    while (fscanf(f, "%s %d", name, &score) == 2) {
        printf("%s scored %d\n", name, score);
    }
    fclose(f);
    return 0;
}

Output (on your own computer with gcc – the simple C runner in the browser editor can't run this one)

Asha scored 90
Ben scored 75
  • fprintf works like printf, but writes into the file.
  • fscanf works like scanf, but reads from the file. It returns how many values it read, so the loop stops when it can't read a full line any more.

Reading line by line

#include <stdio.h>

int main() {
    FILE *f = fopen("notes.txt", "w");
    fprintf(f, "buy milk\ncall mum\nlearn C\n");
    fclose(f);

    char line[100];
    int number = 1;
    f = fopen("notes.txt", "r");
    while (fgets(line, 100, f) != NULL) {
        printf("%d: %s", number, line);
        number++;
    }
    fclose(f);
    return 0;
}

Output (on your own computer with gcc – the simple C runner in the browser editor can't run this one)

1: buy milk
2: call mum
3: learn C

Common mistake: Not checking whether fopen returned NULL. If the file doesn't exist (in "r" mode), using the pointer crashes the program.

Tip: Files need a real computer, so the browser challenges don't use them. Try these examples with gcc on your own machine.

HOME LABS COMMUNITY DASHBOARD