Files
Files — data that survives
- Variables in RAM disappear when the program ends.
- To keep data (high scores, records, settings), a program writes to a file on secondary storage.
- Files also let programs share data and restart from a saved state.
Why use files
- Persistence — data stays between program runs.
- Sharing — other programs can read the same file.
- Recovery — a program can restart from a saved state.
Practice
Why does a program write data to a file rather than keeping it in a variable?
RAM is volatile, so data is lost on exit. A file on secondary storage persists between runs.
Reading and writing
OPENFILE "data.txt" FOR READ // or FOR WRITE, FOR APPEND
WHILE NOT EOF("data.txt") DO
READFILE "data.txt", LineString
OUTPUT LineString
ENDWHILE
CLOSEFILE "data.txt"
- Open a file before use and close it after.
EOFtests for the end of file before reading.FOR WRITEoverwrites;FOR APPENDadds to the end.- Always close every file, or buffered writes may be lost and the file may stay locked.
Practice
What does EOF test for?
EOF (end of file) is checked before each read so the loop stops when there is no more data.
Practice
Opening a file FOR APPEND rather than FOR WRITE means:
APPEND adds to the end; WRITE overwrites the existing contents.
Practice
Why must you always close a file after using it?
Closing flushes buffered writes to disk and releases the lock so other programs can use the file.
You've got it
Key idea
- files give persistence — data survives after the program ends (unlike RAM)
- OPENFILE (READ/WRITE/APPEND) → READFILE/WRITEFILE → CLOSEFILE
EOFtests the end of file before reading- always close files, or buffered data can be lost