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
fopen(name, mode)opens a file and returns aFILE *, a handle you pass to the other functions. It returnsNULLif it fails.- The mode says what you intend:
"r"read (the file must exist),"w"write (creates the file, or erases it if it already exists),"a"append (adds to the end). fprintf(f, ...)works exactly likeprintf, but writes to the file.fscanf(f, ...)isscanffor files, andfgetc(f)reads one character (or returnsEOFat the end).fclose(f)closes the file. Writes are buffered (collected in memory and written in chunks for speed), and closing flushes the buffer to disk. Until then, the last writes may still be sitting in memory, so reading the file back before closing it, or a crash, can lose the end of your output. Close every file when you're done with it.
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.