File Handling
Programming
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. In this example the file holds a single line:
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"
Common exam question
Writing pseudocode to store or read a text file
Question: Write pseudocode to input a value and store it in a named text file, or to read a file into a variable, then close the file (3–5 marks).
Asked in 4 of the 17 papers, three times to store data and once to read it. Opening, writing or reading, and closing are separate mark points: OPENFILE "Scores.txt" FOR WRITE to store (FOR READ to read), then WRITEFILE "Scores.txt", Score or READFILE "Scores.txt", Score, then CLOSEFILE "Scores.txt". If the task asks you to input the value, INPUT Score earns a mark too.
Use the filename exactly as given, in every statement: one scheme pays a mark for using it throughout, another credits the opening only with the given name. Closing is a mark point in all four schemes; in the two-file task it needed both files closed. The schemes' example answers show the filename with and without quotation marks; quote it, as a filename is a string.