Computer ScienceExam code: 0984

File Handling

Programming

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:

  1. The flag EndOfFile is initialised to FALSE.
  2. The loop continues while EndOfFile is still FALSE.
  3. Each iteration reads one line into Line.
  4. If the line is empty (an empty string), assume the end of the file has been reached and set EndOfFile to TRUE so the loop ends.
  5. 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.

Build on this topic