Files
| English | Chinese | Pinyin |
|---|---|---|
| secondary storage | 辅助存储器 | fǔ zhù cún chǔ qì |
| persistence | 持久性 | chí jiǔ xìng |
| end of file | 文件结束 | wén jiàn jié shù |
| sequential | 顺序 | shùn xù |
Data that outlives the program
- 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.
Direct (random) access lets a program jump straight to a record without reading the others first.
Serial access must read from the start.
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.

Push and pop change the top pointer; the base pointer stays put
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.
Handling a file: open → use → close
Step through the lifecycle every file follows. The two easy-to-forget parts are testing EOF while reading in a loop, and always closing at the end.
What does EOF test for?
EOF (end of file) is checked before each read so the loop stops when there is no more data.
Match each file-open mode to what it does.
READ reads; WRITE replaces from scratch; APPEND adds to the end without losing what is there.
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.
Serial vs direct access
- Serial/sequential 顺序 files are read in order from the start — simple but slow to search.
- Direct (random) access jumps straight to a record, often using a calculated position.
- Programs read and write text files line by line.
You've got it
- 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