File Handling
Programming · 4 question types
Exam Frequency Analysis
Past paper frequency (2018 to 2024)
This topic accounts for approximately 3% of your exam marks.
OPENFILE, READFILE, WRITEFILE, CLOSEFILE pseudocode operations appear occasionally.
A file must be opened in a mode that tells the operating system what the program intends to do with it. The mode appears after FOR in the OPENFILE statement. CIE pseudocode has two file modes: READ and WRITE.
| Mode | What it does | What happens to existing contents |
|---|---|---|
READ | Opens the file for reading only | Untouched; the file must already exist |
WRITE | Opens the file for writing new content | Erased: if the file already exists, its contents are overwritten |
READ
Used when the program needs to load data from a . The file must already exist; opening a non-existent file in READ mode causes an error.
OPENFILE "students.txt" FOR READ
READFILE "students.txt", Name
OUTPUT Name
CLOSEFILE "students.txt"
WRITE
Used when the program is creating a new file or completely replacing an existing one. If the file already exists, everything in it is wiped out before the new content is written.
OPENFILE "report.txt" FOR WRITE
WRITEFILE "report.txt", "Sales Report 2024"
WRITEFILE "report.txt", "Total: £125,000"
CLOSEFILE "report.txt"
Important: opening a file that already has data in
WRITEmode destroys its existing contents before writing. There is no mode that adds to a file while leaving it intact, so keeping the old data is something the program has to arrange for itself.
There is no APPEND mode
Some programming languages offer an "append" mode that adds new content to the end of a file without erasing what is already there. CIE pseudocode does not. WRITE is the only mode that puts data into a file, and it always starts the file again from empty.
To end up with the old content and something new, do the job in two stages: open the file FOR READ and store what it contains, close it, then reopen it FOR WRITE and write the old content back out followed by the new line.
OPENFILE "log.txt" FOR READ
READFILE "log.txt", OldEntry
CLOSEFILE "log.txt"
OPENFILE "log.txt" FOR WRITE
WRITEFILE "log.txt", OldEntry
WRITEFILE "log.txt", "New entry added at the end"
CLOSEFILE "log.txt"
The file is closed before it is reopened because a file may only be open in one mode at a time.
Choosing the right mode
| Goal | Use mode |
|---|---|
| Load existing data into the program | READ |
| Create a fresh new file (or replace an old one entirely) | WRITE |
| Add a new record while keeping what is already there | READ the old data, then WRITE it back with the new record |