File processing
File processing
- 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.
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"
Practice
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.
Practice
EOF(name) returns TRUE when:
EOF is checked before each read so the loop stops at the end of the file.
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.
Practice
When searching a file for a value, the loop condition usually includes:
Stopping when found avoids reading the rest of the file unnecessarily.
Practice
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).
Practice
A common file-handling pitfall is:
Not closing a file can lose buffered writes and lock others out; always close it.
You've got it
Key idea
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