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.
The most common file-reading pattern is to process every line, one at a time, until the end of the file is reached.
A standard CIE-style approach uses an end-of-file 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:
EndOfFile is initialised to FALSE.EndOfFile is still FALSE.Line.EndOfFile to TRUE so the loop ends.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.
Example — A file employees.txt holds employee records, with each employee taking four consecutive lines: name, department, salary, age. Read every record and print it.
OPENFILE "employees.txt" FOR READ
EndOfFile ← FALSE
WHILE NOT EndOfFile DO
READFILE "employees.txt", Name
READFILE "employees.txt", Department
READFILE "employees.txt", Salary
READFILE "employees.txt", Age
IF Name = "" THEN
EndOfFile ← TRUE
ELSE
OUTPUT "Name: ", Name
OUTPUT "Department: ", Department
OUTPUT "Salary: ", Salary
OUTPUT "Age: ", Age
OUTPUT ""
ENDIF
ENDWHILE
CLOSEFILE "employees.txt"
For an input file containing:
Greg
Sales
39000
43
Lucy
Human Resources
26750
28
the program outputs both employees' records, one after the other, then stops when the next attempted name-read returns an empty string.