Programming · 4 question types
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.
| 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 |
APPEND | Opens the file for adding to the end | Untouched; new data is added after the existing content |
Used when the program needs to load data from a file. 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"
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 with existing data in
WRITEmode destroys its contents. If you only want to add data, useAPPENDinstead.
Used to tack new lines onto the bottom of a file that already has content, without disturbing what is already there.
OPENFILE "log.txt" FOR APPEND
WRITEFILE "log.txt", "2024-05-17 10:32: user logged in"
CLOSEFILE "log.txt"
If the file does not yet exist when APPEND is used, the OS usually creates it (an empty file is "appended to" the same as a new file).
| 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 to an existing log or list | APPEND |