Files are how a program's work survives after it exits — fopen opens the door, fclose closes it.
1 FILE is a handle
fopen returns a FILE pointer — your ticket for every read and write that follows.
2 Modes matter
"r" reads an existing file, "w" creates or erases, "a" appends at the end.
3 Check for NULL
fopen fails on missing files or bad paths and returns NULL — always test before writing.
4 Always fclose
fclose flushes buffered bytes to disk and releases the file — forget it and you may lose data.
Data that outlives the program
FILE is a handle1fopen returns a FILE pointer — your ticket for every read and write that follows. Modes matter2"r" reads an existing file, "w" creates or erases, "a" appends at the end. Check for NULL3fopen fails on missing files or bad paths and returns NULL — always test before writing. Always fclose4fclose flushes buffered bytes to disk and releases the file — forget it and you may lose data. 4 building blocks make up Data that outlives the program
One handle at a time: open in write mode, close, reopen in read mode, close again.
process decision input / output start / end Press play — fprintf sends text into the file, fgets brings it straight back out.
preprocessThe preprocessor pastes in stdio.h — FILE, fopen and friends come from there.
Memory
no variables yet — press play
Console
output appears as the program runs…
Click a call, then click what it does to lock the pair.
6 conceptsTap a card to expand ?fopen("a.txt", "r")drops into place
?fopen("a.txt", "w")drops into place
?fopen("a.txt", "a")drops into place
?fprintf(f, "%d", n)drops into place
?fgets(buf, 40, f)drops into place
?fclose(f)drops into place
Write one line, then read the whole file back — what appears on screen?
Your predicted output — one line per console line
Hint: Mode "w" writes first, then "r" reads the same file back — fgets returns each line, \n included.
01fopen(path, mode) returns a FILE* — your handle for all file operations.
02"w" erases immediately, "a" appends, "r" only reads.
03fprintf writes to files the way printf writes to the screen.
04Always check fopen for NULL before using the handle.
05fclose is not optional — it flushes buffered bytes to disk.