C/C++ Arena

Step 1 of 8

Write a file, read it back

Everything a program keeps in variables disappears when it exits. To keep data between runs, or to read data someone else produced, programs use files. C's file functions live in <stdio.h>, the same header as printf.

The workflow is always the same: open, read or write, close.

#include <stdio.h>

int main(void) {
    FILE *f = fopen("todo.txt", "w");
    if (f == NULL) return 1;
    fprintf(f, "buy milk\n");
    fprintf(f, "call %s at %d\n", "Ada", 5);
    fclose(f);

    f = fopen("todo.txt", "r");
    if (f == NULL) return 1;
    int c, lines = 0;
    while ((c = fgetc(f)) != EOF) {
        if (c == '\n') lines++;
    }
    fclose(f);
    printf("%d lines saved\n", lines);
    return 0;
}
2 lines saved

The pieces

In fact printf is just fprintf(stdout, ...): the screen is treated as a file called stdout.

On this site, each run gets its own private, empty folder, so your program can create and read files freely.

Your turn: open scores.txt for writing, then for reading.

Next: Reading lines with fgets