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.
The most common file-reading pattern is to process every line, one at a time, until the end of the file is reached.
The end-of-file flag pattern
CIE pseudocode has no EOF function, so the program cannot ask the file whether it has run out of data. Instead the standard approach uses a (an empty line marking the end of the data) together with an end-of- flag (a Boolean) and a WHILE loop:
DECLARE EndOfFile : BOOLEAN
DECLARE Line : STRING
OPENFILE "students.txt" FOR READ
EndOfFile ← FALSE
WHILE NOT EndOfFile DO
READFILE "students.txt", Line
IF Line = ""
THEN
EndOfFile ← TRUE
ELSE
OUTPUT Line
ENDIF
ENDWHILE
CLOSEFILE "students.txt"
How it works:
- The flag
EndOfFileis initialised toFALSE. - The loop continues while
EndOfFileis stillFALSE. - Each iteration reads one line into
Line. - If the line is empty (an empty string), assume the end of the file has been reached and set
EndOfFiletoTRUEso the loop ends. - Otherwise, process the line (here, output it).
Why a WHILE loop, not a FOR loop?
A FOR loop is counter-controlled: you have to know in advance how many iterations to run. The program does not know how many lines a file contains until it starts reading. A WHILE loop with a condition that checks for end-of-file is the natural choice.