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 task

Open scores.txt for writing, then for reading.

Challenge 2

Fill in the three missing file functions: one writes formatted text into the file, one closes it, and one reads a line back. The program prints the two lines it wrote.

Challenge 3

Write the squares of 1 to 5 into squares.txt, one per line, and close it. Then open it again, read the numbers back, and print their sum: sum 55. The sum must come from reading the file, not from the loop that wrote it.

Next: Reading lines with fgets