- File modes and the open → process → close pattern
Open a file in a mode, read or write it, then always close it.
Data in variables lives in RAM and is lost when the program ends. A file stores data on secondary storage, so it is persistent — it survives the run and can be read back later.
All file handling in 9618 follows the same three-stage lifecycle:
- Open the file with a mode — what you intend to do.
- Process the file — read records/lines from it, or write them to it.
- Close the file when finished, so the data is saved and the file is released.
The three modes are:
| Mode | What it does | Use it to… |
|---|---|---|
| FOR READ | opens an existing file to read from the start | read data back |
| FOR WRITE | creates a new, empty file (overwrites any existing one) | start a fresh file |
| FOR APPEND | opens an existing file and writes at the end | add to existing data |
The Cambridge pseudocode commands are:
OPENFILE "Data.txt" FOR READ // or FOR WRITE / FOR APPEND
READFILE "Data.txt", Variable // read the next line into Variable
WRITEFILE "Data.txt", Value // write one line
CLOSEFILE "Data.txt" // close it (saves + releases)
The EOF function tells you when reading has reached the end:
EOF("filename") returns TRUE at the end of the file, FALSE while lines remain.
So the standard read loop runs WHILE NOT EOF — checking EOF before each read:
DECLARE Line : STRING
OPENFILE "Data.txt" FOR READ
WHILE NOT EOF("Data.txt") DO
READFILE "Data.txt", Line
OUTPUT Line
ENDWHILE
CLOSEFILE "Data.txt"
- Files give persistent storage; variables (RAM) are temporary.
- Lifecycle: OPENFILE → READFILE/WRITEFILE → CLOSEFILE.
- FOR READ reads; FOR WRITE makes a fresh file; FOR APPEND adds to the end.
- Loop WHILE NOT EOF("name") and CLOSEFILE every file you open.
See the full worked example for file processing and exception handling →