File processing
| English | Chinese | Pinyin |
|---|---|---|
| overwrites | 覆盖 | fù gài |
| append | 追加 | zhuī jiā |
| temporary file | 临时文件 | lín shí wén jiàn |
Reading and writing records
- Programs read and write files to keep data between runs.
- A small set of operations covers reading, searching and updating.
- A few common pitfalls cause real bugs.
File access route
Follow a file from storage to program and back safely.
The operations
OPENFILE name FOR READ | WRITE | APPEND— READ opens an existing file, WRITE creates/overwrites 覆盖, APPEND 追加 adds to the end.READFILE name, line·WRITEFILE name, value·CLOSEFILE name·EOF(name)is TRUE at the end.
OPENFILE "names.txt" FOR READ
WHILE NOT EOF("names.txt") DO
READFILE "names.txt", thisName
OUTPUT thisName
ENDWHILE
CLOSEFILE "names.txt"

File handling: open the file, read or write records, then close it
What does opening a file FOR WRITE do to existing contents?
WRITE creates or overwrites the file. To keep existing contents and add more, use APPEND.
Match each file operation to what it does.
WRITE overwrites, APPEND adds; EOF marks the end; the search loop stops early once the value is found.
Searching and updating
- To search, read line by line and stop when found (
WHILE NOT EOF AND NOT found). - Most languages can't edit a text file in place. To update: open the original for READ and a temporary file 临时文件 for WRITE; copy each line (changed or not); close both; then replace the original with the temp file. The same pattern deletes lines (skip them) or inserts lines.
When searching a file for a value, the loop condition usually includes:
Stopping when found avoids reading the rest of the file unnecessarily.
To update a text file when in-place editing is not possible, you:
Copy each line (changed or not) to a temp file, then swap it in for the original.
Pitfalls
- Forgetting to close a file → buffered data may be lost.
- Opening for WRITE when you meant APPEND → overwrites everything.
- Reading past EOF, and hard-coded paths (use constants for portability).
- Files can be serial, sequential or random (direct-access); this is file-processing.
Forgetting to close a file can lose buffered writes and lock other programs out — so you should always close a file when finished.
Closing flushes buffered data to disk and releases the lock — a FINALLY block is a good place to guarantee it.
You've got it
OPENFILE(READ/WRITE/APPEND) → READFILE/WRITEFILE → CLOSEFILE;EOFmarks the end- WRITE overwrites, APPEND adds — don't mix them up
- update in place via a temporary file, then replace the original
- always close files; avoid reading past EOF and hard-coded paths