File Handling

Computer Science revision notes · Cambridge (CIE) · 0984

1. Why files are used

A running program holds all its data in RAM, which is volatile: the moment the program ends or the computer is turned off, every variable disappears (topic 9). For data to survive across program runs, it must be saved to secondary storage as a .

Files are how programs:

  • Remember user data between sessions (a saved game, a contact list, a logged-in session).
  • Read input data prepared elsewhere (a list of student names, a configuration file, a CSV export).
  • Write reports and logs that other programs or people can read later.
  • Share data between programs that do not run at the same time.

The focus here is on text files: simple human-readable files made of lines of text.

Common exam question

Why a program stores data in a file

Question: Explain or outline why it is useful for a program to store its data in a file (2 marks).

Asked in 2 of the 17 papers. Make two different points. A file is kept on non-volatile storage, so the data is permanent and is not lost when the program ends or the computer is switched off. Because it is kept, the data can be retrieved and used again later, by the same program or by a different one. One scheme also credits the idea that a file can be moved to another computer.

Writing that the data is permanent and that it will not be lost makes one point twice, and earns one mark: make the reuse point your second.

The basic life cycle

Working with a file always follows the same four-step pattern:

  1. Open the file in the appropriate mode (read or write).
  2. Read lines from it or write lines into it.
  3. Continue until the work is done.
  4. Close the file.

Skipping the close step is one of the most common bugs in file-handling code. The next section explains why.

2. CIE pseudocode file-handling commands

CIE pseudocode uses a small set of dedicated keywords for file operations.

OperationPseudocodePython equivalent
Open for a given modeOPENFILE "filename.txt" FOR <mode>file = open("filename.txt", "r") (or "w")
Read one lineREADFILE "filename.txt", LineVariableline = file.readline()
Write one lineWRITEFILE "filename.txt", TextToWritefile.write("text\n")
Close the fileCLOSEFILE "filename.txt"file.close()

The CIE file commands always include the filename so the operation knows which file it is acting on.

3. File modes: READ and WRITE

A file must be opened in a mode that tells the operating system what the program intends to do with it. The mode appears after FOR in the OPENFILE statement. CIE pseudocode has two file modes: READ and WRITE.

ModeWhat it doesWhat happens to existing contents
READOpens the file for reading onlyUntouched; the file must already exist
WRITEOpens the file for writing new contentErased: if the file already exists, its contents are overwritten

READ

Used when the program needs to load data from a . The file must already exist; opening a non-existent file in READ mode causes an error.

OPENFILE "students.txt" FOR READ
READFILE "students.txt", Name
OUTPUT Name
CLOSEFILE "students.txt"

WRITE

Used when the program is creating a new file or completely replacing an existing one. If the file already exists, everything in it is wiped out before the new content is written.

OPENFILE "report.txt" FOR WRITE
WRITEFILE "report.txt", "Sales Report 2024"
WRITEFILE "report.txt", "Total: £125,000"
CLOSEFILE "report.txt"

Important: opening a file that already has data in WRITE mode destroys its existing contents before writing. There is no mode that adds to a file while leaving it intact, so keeping the old data is something the program has to arrange for itself.

There is no APPEND mode

Some programming languages offer an "append" mode that adds new content to the end of a file without erasing what is already there. CIE pseudocode does not. WRITE is the only mode that puts data into a file, and it always starts the file again from empty.

To end up with the old content and something new, do the job in two stages: open the file FOR READ and store what it contains (in the example below, a single line), close it, then reopen it FOR WRITE and write the old content back out followed by the new line.

OPENFILE "log.txt" FOR READ
READFILE "log.txt", OldEntry
CLOSEFILE "log.txt"

OPENFILE "log.txt" FOR WRITE
WRITEFILE "log.txt", OldEntry
WRITEFILE "log.txt", "New entry added at the end"
CLOSEFILE "log.txt"

The file is closed before it is reopened because a file may only be open in one mode at a time.

Choosing the right mode

GoalUse mode
Load existing data into the programREAD
Create a fresh new file (or replace an old one entirely)WRITE
Add a new record while keeping what is already thereREAD the old data, then WRITE it back with the new record

4. Closing a file: why CLOSEFILE matters

Every file that has been opened must be closed before the program ends. Forgetting CLOSEFILE can lose data or corrupt the file.

When a program writes to a file, the operating system does not always send the data straight to the disk. Instead, the data sits in a in RAM, ready to be written in efficient chunks. The file is only flushed (written out to disk) when:

  • The buffer fills up.
  • The program closes the file.
  • The operating system shuts the program down (sometimes).

If the program ends without closing the file, the buffered data may never reach the disk, and the file is left incomplete or empty.

Other things CLOSEFILE does

  • Frees the file handle so another program can open the file.
  • Releases system resources (memory, OS structures) used to track the open file.
  • Marks the file as available for reading by other parts of the system.

Common slip: forgetting CLOSEFILE at the end of a file-writing algorithm. Past mark schemes give closing the file a mark of its own, and the algorithm is incomplete without it.

5. Reading a file line by line

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-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:

  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.

6. Writing to a file

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.

7. File-handling pitfalls

Common mistakes that lose marks (and lose data in real programs):

  • Opening a in WRITE mode when you meant to keep its existing data. WRITE mode overwrites the file, destroying all existing contents.
  • Forgetting CLOSEFILE. Buffered data may not reach the disk; the file may be incomplete or corrupt.
  • Reading past the end of the file without checking for it. There is no EOF function in CIE pseudocode, so always test the line you have just read against a sentinel value and stop the loop with a Boolean flag.
  • Opening a file that does not exist in READ mode. Causes a runtime error; check it exists first if necessary.
  • Mixing modes. A single OPENFILE opens for one specific mode. To switch between reading and writing, close and reopen the file.
  • Forgetting to handle blank lines when reading. An empty line is often used as the end-of-file sentinel in the CIE pseudocode pattern, so be careful with files that genuinely contain blank lines in the middle.
  • Always make a backup of important text files before writing to them. A program with a bug can wipe out hours of work in milliseconds.