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.
Writing uses the WRITEFILE keyword once the file has been opened FOR WRITE.
Writing a new file (WRITE mode)
Used when starting fresh, or when overwriting an existing file:
OPENFILE "report.txt" FOR WRITE
WRITEFILE "report.txt", "Sales Report 2024"
WRITEFILE "report.txt", "Total: £125,000"
WRITEFILE "report.txt", "Customers: 1,432"
CLOSEFILE "report.txt"
After this runs, report.txt contains exactly those three lines. Any previous content is gone, because opening in WRITE mode overwrites the file.
Adding to existing data
Because WRITE is the only output mode and it clears the file first, adding a line without losing the existing ones means reading the old content in before writing everything back out:
OPENFILE "log.txt" FOR READ
READFILE "log.txt", OldLine
CLOSEFILE "log.txt"
OPENFILE "log.txt" FOR WRITE
WRITEFILE "log.txt", OldLine
WRITEFILE "log.txt", NewLine
CLOSEFILE "log.txt"
Writing to a file in pseudocode
What comes up: write pseudocode to open a file, store a value to it, and close it (a 3-mark question).
Write (three marks): (1) Open the file in WRITE mode — OPENFILE "filename.txt" FOR WRITE. (2) Write the variable to the file — WRITEFILE "filename.txt", VariableName. (3) Close the file — CLOSEFILE "filename.txt". Each of these three lines is a separate mark point.
Watch out: CLOSEFILE is its own credited mark — the mark scheme awards it independently, so dropping it loses a mark even though the data appears written. Also, opening in WRITE mode silently destroys any existing file contents; if the question needs the existing data kept, read it in first and write it back out along with the new data.