O Level Computer Science 2210 · Area 2 · Algorithms, programming and logic

File handling in programs

A program's variables disappear when it ends, so anything that must survive is written to a file on backing store. This page covers the four Cambridge commands - OPENFILE, READFILE, WRITEFILE and CLOSEFILE - and the order they must appear in. Marks are lost by opening a file in the wrong mode, by forgetting that WRITE replaces the whole file, and by reading records in the wrong order without a loop.

Not started

Syllabus coverage

  • Understand the purpose of storing data in a file to be used by a program
  • Open a file, stating the mode of operation, before reading from or writing to it
  • Read single items of data and lines of text from a file using READFILE
  • Write single items of data and lines of text to a file using WRITEFILE
  • Close a file with CLOSEFILE when it is no longer needed
  • Use a file to keep data between runs of a program, rather than re-entering it each time

Part of the O Level Computer Science syllabus 2210.

A file keeps data after the program endsVariables live only while the program runs; a file keeps its data on backing store.Open, use, then close - a file left open may not be written correctly.The order a program must useOPENFILE the file for reading or writingREADFILE a record, or WRITEFILE a recordrepeat until every record is usedCLOSEFILE to finishThe file on diskrecord 1fields in orderrecord 2fields in orderrecord 3fields in orderdata survives after the program ends
A program shown opening a file, reading two records from it and writing one record before closing it, with the file drawn as consecutive records stored on backing store.

Why a program stores data in a file

The variables of a running program live in RAM, and RAM is cleared when the program ends or the computer is switched off. Anything the program must keep - the scores of a game, the members of a club, the orders placed today - would be lost. Storing it in a file on backing store gives it a life beyond the run that created it.

That is the purpose the syllabus asks for: data is written to a file so that it can be used by a program later. The same file can be read by the next run of the same program, by a different program, or on a different computer, and the user does not have to type the data in again. A file also holds far more data than a program would sensibly ask a user to enter by hand.

A file is not the same as a database. A file is a sequence of data held by the operating system and opened by name; the program itself must know the order of the items in it. That simplicity is why files are used for settings, logs, saved games and simple lists, where a single table would be more structure than the job needs.

  • Data survives after the program ends and after the computer is switched off.
  • The data is entered once and reused by later runs, so it does not have to be typed again.
  • A file can hold more data than a user could reasonably key in, and can be transferred between programs.
  • The program must know the order of the data in the file, because a plain file has no field names of its own.
The mark scheme phrase is 'so the data can be used again / is not lost when the program ends'. Saying only 'to save it' is too vague to score.

What a file actually holds

A file is a sequence of data on backing store, one item after another, and the program reads it in that order. If the data describes things - members, products, bookings - it is normally stored as records, with the same fields in the same order in every record. The file is then a long line of records with no gaps, and the only way to reach record 50 is to read the 49 before it.

A record in a text file is usually written as one line of text, with the fields separated by a comma. The program reads a whole line, splits it at the commas, and puts the pieces into variables. Reading and writing a line at a time is what the syllabus means by 'read and write a line of text', as opposed to reading and writing single items of data such as one number or one name.

This matters when a question asks you to design a file. Decide what one record contains, decide the order of its fields, and write every record in that same order. A program that reads the fields in a different order from the one they were written in will load prices into names and names into quantities, and nothing will raise an error.

TermMeaning
RecordOne complete set of related fields, such as one member's number, name and fee paid
FieldOne item within a record, such as the member's name
Line of textOne record written as characters ending with a newline; the fields are separated by a delimiter such as a comma
Sequential accessReading the file from the start, one item or record after another, because there is no index to jump to record 50 directly

Opening a file: the two modes

Before a program reads or writes, it opens the file and states the mode, which tells the operating system what the program intends to do. In Cambridge pseudocode this is:

OPENFILE <file identifier> FOR <file mode>

There are two modes in this syllabus. READ means data will be read from an existing file. WRITE means data will be written to the file; a new file is created, and any data already in that file is lost. A file is opened in one mode at a time, so a program that needs to read a file and then change it opens it twice - once for reading, and once, after closing it, for writing.

The file identifier is the name of the file, given as a string: `OPENFILE "Members.txt" FOR READ`. The program and the operating system now share a connection to the file, and every later READFILE or WRITEFILE names the file again so that it is clear which file is meant.

The mode is the part students lose marks on. WRITE does not add to the end of a file - it replaces the file. A program that opens its saved data FOR WRITE at the start of a run, meaning to update one record, has destroyed every record before it has read any of them.

WRITE = new file, old contents gone. If the data must be kept, read the old file first, close it, then open the file for writing and write the records back.

Reading from a file

Once the file is open for reading, data is taken from it one item at a time:

READFILE <file identifier>, <variable>

The next item in the file is read and assigned to the variable. The program does not say which item - the file has a current position, and each read moves it forward. This is why the reads must happen in the order the data was written, and why a loop is used to read a whole file of records.

The loop needs to know when to stop. A question usually tells you how many records there are, which allows a count-controlled loop: read and process each record a fixed number of times. Otherwise the last record is a sentinel - a value that cannot be real data, such as the word END - and the program tests for it after reading and stops when it appears.

DECLARE MemberName : STRING OPENFILE "Members.txt" FOR READ FOR Index ← 1 TO 40 READFILE "Members.txt", MemberName OUTPUT MemberName NEXT Index CLOSEFILE "Members.txt"

Reading does not remove data from the file, and reading the same file again in a later run gives the same records, because nothing has been written. Only WRITEFILE changes a file.

Writing to a file

Writing uses the matching command, after the file has been opened FOR WRITE:

WRITEFILE <file identifier>, <variable>

The value of the variable is written into the file as the next item. The variable must already hold the value - WRITEFILE writes what is in the variable, it does not ask the user for anything. So a program that saves three numbers inputs them first and then writes each one.

Each write appends after the previous one, so the order of the writes decides the order of the file. Writing a record means writing its fields one after another in the agreed order, or building a line of text with the fields separated by commas and writing that line. A loop writes many records in the same way that a loop reads them:

OPENFILE "Scores.txt" FOR WRITE FOR Index ← 1 TO 30 WRITEFILE "Scores.txt", Scores[Index] NEXT Index CLOSEFILE "Scores.txt"

Because the file was opened FOR WRITE, it now contains exactly the 30 values written in this run. Whatever was in the file before is gone - which is correct here, because the program is saving a fresh set of scores.

CommandFormWhat it does
OPENFILEOPENFILE "Data.txt" FOR READConnects the program to an existing file for reading
OPENFILEOPENFILE "Data.txt" FOR WRITECreates the file for writing, losing any existing contents
READFILEREADFILE "Data.txt", ValueReads the next item into Value
WRITEFILEWRITEFILE "Data.txt", ValueWrites the value of Value as the next item
CLOSEFILECLOSEFILE "Data.txt"Ends the program's use of the file and saves the changes

Closing the file

A file is closed when the program has finished with it:

CLOSEFILE <file identifier>

Closing tells the operating system that the program has finished, so the file can be used by another program and any data still held in a buffer is written to the disk. Data written just before a program crashes may never reach the file if the file was not closed, which is why close comes before the program ends rather than being left out.

Every file that was opened must be closed, and each is closed by name. A program that reads one file and writes another closes both, in any order, after the last read and write. Leaving a file open does not usually stop the program that opened it, but it can lock the file so that another program cannot open it, and it risks losing the last records written.

The full sequence is always the same: open, then read or write as many times as needed, then close. A question that asks you to 'use the file' is asking for that sequence with a loop in the middle.

Open, use, close. If a pseudocode answer opens a file and never closes it, expect to lose the mark for closing even when every other line is correct.

A complete pattern: read, process, write back

The most common file question describes a program that must keep its data between runs: read the records in, change one of them, and save them all again. Because WRITE replaces the file, the program reads every record into an array, closes the file, changes the array, then reopens the file for writing and writes the array back.

DECLARE MemberName : ARRAY[1:40] OF STRING DECLARE Index : INTEGER OPENFILE "Members.txt" FOR READ FOR Index ← 1 TO 40 READFILE "Members.txt", MemberName[Index] NEXT Index CLOSEFILE "Members.txt" // change one name in the array here OPENFILE "Members.txt" FOR WRITE FOR Index ← 1 TO 40 WRITEFILE "Members.txt", MemberName[Index] NEXT Index CLOSEFILE "Members.txt"

The array is what makes this possible: the records are held in RAM while the file is closed and reopened, so nothing is lost when the old file is replaced. Without the array, the program would have to read and write at the same time, which a single file opened in one mode does not allow.

The same shape works for a log file, except that the program does not need to read the old records at all: it opens FOR WRITE, writes the new records, and closes. The choice depends on whether the old data must be kept.

When file handling goes wrong

Almost every file-handling error in an exam comes from one of four causes, and each has a visible symptom. Opening in the wrong mode is the most damaging: a file opened FOR WRITE is emptied the moment it is opened, so a program that meant to add one record can wipe the whole file before it reads anything.

Reading past the end of the file is the second. A loop that runs one time too many reads whatever follows the last record, or fails; a loop that runs one time too few silently ignores the last record. The count in the loop must match the number of records, which is why the question usually tells you how many there are.

The third is a mode mismatch - opening FOR READ and then calling WRITEFILE, or the reverse. The command does not match what the file was opened for, so the operation fails. The fourth is forgetting CLOSEFILE, which risks the last records never reaching the disk and leaves the file locked to other programs.

None of these produces a helpful message while the program is being written. They show up as missing data, duplicated data or an empty file, which is why the order of the four commands is worth learning as a pattern rather than as four separate facts.

  • Opened FOR WRITE when the old data was needed: the file is emptied at the moment it is opened.
  • Loop count too high: the program reads past the last record; too low: the last record is ignored.
  • READFILE used on a file opened FOR WRITE, or WRITEFILE on a file opened FOR READ.
  • CLOSEFILE missing: buffered data may be lost and the file stays locked.

Key terms you must be able to define

File
A named collection of data on backing store that a program can open, read from or write to, and that survives after the program ends.
File mode
What the program intends to do with an open file: READ to take data from it, or WRITE to put data into it, creating the file and losing any existing contents.
OPENFILE
The command that connects a program to a named file in a stated mode before any reading or writing takes place.
READFILE
The command that reads the next item of data from an open file and assigns it to a variable.
WRITEFILE
The command that writes the current value of a variable into an open file as the next item of data.
CLOSEFILE
The command that ends the program's use of a file, saving any buffered data and releasing the file for other programs.
Record
One complete set of related fields in a file, such as one member's number, name and subscription paid.
Sentinel value
A value that cannot occur in the real data, placed at the end of a file so that a program reading it knows when to stop.

In context

2210 sets its questions inside systems a student already uses - a school network, a phone, a supermarket till, a vending machine, a website. These show how the theory is applied to a context you have not seen before, then you answer for the system you are given.

Saving a game's high scores

A game keeps the best five scores in a file. At the end of a game it opens `"HighScores.txt"` FOR WRITE and writes the five values with a loop, so the next player sees the updated table when the program starts again. Without the file the table would be rebuilt from nothing on every run.

A club's membership list

A club secretary's program stores one line per member, with the member number, surname and whether the subscription is paid, separated by commas. Each run reads the lines with READFILE, shows the members who have not paid, and writes the whole list back after the secretary marks a payment. The read-into-array, close, reopen-for-write pattern is used because WRITE would otherwise erase the list before it was read.

A temperature logger

A sensor program takes a reading every minute and writes it to a file, one value per line. It opens the file FOR WRITE at the start of the day and writes each reading as it arrives, closing the file at midnight. A second program opens the same file FOR READ and works out the day's maximum and average by reading the values in a loop until the sentinel at the end.

Copying a file

A program opens `"Original.txt"` FOR READ and `"Copy.txt"` FOR WRITE, reads one line into a string variable, writes that variable to the second file, and repeats until the sentinel is read. It then closes both files. Two files can be open at once as long as each is in the mode that matches what the program does with it.

Flashcards

Click a card to flip it. Mark honestly — the tracker uses this.

Q1Why does a program store data in a file?
So the data is not lost when the program ends or the computer is switched off, and can be used again by a later run or another program without being re-entered.
Q2Give the Cambridge pseudocode command that opens a file for reading.
OPENFILE "Data.txt" FOR READ
Q3What happens to a file that already contains data when it is opened FOR WRITE?
A new file is created and the existing data is lost. WRITE does not add to the end of the file.
Q4Give the command that reads the next item from a file into a variable.
READFILE "Data.txt", Value - the next item is read and assigned to Value.
Q5Give the command that writes a variable's value into a file.
WRITEFILE "Data.txt", Value
Q6Why must a file be closed?
So that buffered data is written to disk and the file is released, allowing other programs to use it. It also marks the end of the program's use of the file.
Q7Can a file be open for reading and writing at the same time?
No. A file is opened in one mode at a time. To change from reading to writing, close it and open it again in the other mode.
Q8How does a program know when it has read every record in a file?
Either it knows how many records there are and uses a count-controlled loop, or the last item is a sentinel value such as END that is tested after each read.
Q9What is a record in a file?
One complete set of related fields, such as one member's number, name and subscription paid, written in the same order as every other record.
Q10Write the four file-handling steps in order for saving data.
OPENFILE ... FOR WRITE, then WRITEFILE for each item, then CLOSEFILE. Reading follows the same pattern with FOR READ and READFILE.
0 of 10 marked as known

Exam-style questions

6 questions, 19 marks. Write your answer and press Mark my answer — it is marked against the scheme and tells you which points you made and what would gain the next mark. You can still reveal the scheme and mark it yourself instead.

StateAO11 mark
State one reason why a program might store its data in a file rather than only in variables.

Mark scheme — tick each point you actually made

Examiner tip: The mark is for persistence - data surviving the run. 'So it can be saved' on its own does not say what it is saved from.
StateAO12 marks
A program must write a new set of results to a file called Results.txt. State the command that opens the file, and state what happens to any data already in that file.

Mark scheme — tick each point you actually made

Examiner tip: The mode must be WRITE and the file name must be in double quotes. The second mark is for saying that the old contents are replaced, not added to.
DescribeAO23 marks
A program reads the 50 records in a file called Members.txt, one name at a time, and displays each name. Describe the file-handling steps the program must carry out, naming the commands it uses.

Mark scheme — tick each point you actually made

Examiner tip: Describe the order, not just the commands: open, loop with read, close. The loop count is 50 because the question gives 50 records.
GiveAO24 marks
A program holds 20 daily takings in a one-dimensional array called Takings, indexed 1 to 20. Give pseudocode that saves all 20 values to a file called Takings.txt.

Mark scheme — tick each point you actually made

Examiner tip: The order is open, loop, write each element, close. Writing the array identifier without an index writes nothing useful, because a file takes one item at a time.
ExplainAO24 marks
A club's program reads its membership file into an array, lets the secretary change one member's details, and then saves the file again. Explain why the program reads the whole file into an array before opening it for writing.

Mark scheme — tick each point you actually made

Examiner tip: Two ideas earn the marks: WRITE empties the file, and the array is what preserves the records in the meantime. Say both.
DescribeAO25 marks
A program copies every line of text from Source.txt into Backup.txt. Describe how the program uses the two files, including how it decides when to stop.

Mark scheme — tick each point you actually made

Examiner tip: Two files are open at once here, which is allowed because each has its own mode. Do not forget to close both at the end.

Exam technique for this topic

  • Write the four commands in order and never leave one out: OPENFILE with a mode, the READFILE or WRITEFILE calls, then CLOSEFILE. An answer that opens the file and reads from it but never closes it loses that mark.
  • Match the command to the mode. READFILE only works after FOR READ, and WRITEFILE only after FOR WRITE. If a question needs both, the file is opened, closed, then opened again in the other mode.
  • Say what WRITE does to existing data: it creates a new file and the old contents are lost. Questions about saving an updated list depend on this point.
  • Use a loop for a file of records and make the number of repetitions match the number of records. If the question does not give a count, test for a sentinel value after each read.
  • Keep the file name as a string and repeat it exactly in every command: `"Members.txt"`, not Members.txt or 'Members'. The identifier is the file's name, not a variable.

Why students lose marks here

A student wroteA student wrote `OPENFILE "Members.txt" FOR WRITE` at the start of a program that needed to read the existing members and add one new member.
Why it loses marksOpening a file FOR WRITE creates a new file and discards the old contents immediately. By the time the program tries to read the existing records, there are none left to read.
The answer that scoresOpen FOR READ first, read the records into an array, then CLOSEFILE. Add the new member to the array, open the file FOR WRITE, write all the records back and close it again. A file cannot be read and written in the same open.
A student wroteA student finished a file-handling answer without a CLOSEFILE command.
Why it loses marksThe file is left open. Data still held in a buffer may never be written to disk, so the last records can be missing, and the file stays locked so that another program cannot open it.
The answer that scoresEvery opened file must be closed by name once the last read or write has been done: `CLOSEFILE "Members.txt"`. The sequence is open, use, close - for each file the program opens.
A student wroteA student read a file of 40 records with `FOR Index ← 1 TO 40` but declared the array as `ARRAY[1:30]` because that was the size in an earlier part of the question.
Why it loses marksThe loop reads 40 records into an array with only 30 elements, so the last ten values are written outside the array's bounds.
The answer that scoresThe array must be large enough for every record that will be read: `DECLARE MemberName : ARRAY[1:40] OF STRING`, with the loop running 1 to 40. The count in the loop, the size of the array and the number of records in the file must agree.
A student wroteA student wrote `WRITEFILE "Scores.txt", 25` to store a mark.
Why it loses marksWRITEFILE writes the value of a variable. A literal such as 25 is not a variable, and the command cannot be used to write a fixed value directly.
The answer that scoresAssign the value first, then write the variable: `Score ← 25` followed by `WRITEFILE "Scores.txt", Score`. The same applies to READFILE, which needs a variable to receive the value it reads.

Where this fits in O Level Computer Science 2210

This page is one topic of Cambridge O Level Computer Science 2210. O Level Computer Science 2210 is the course home: every area and every topic in Cambridge's own order, the papers you sit and what each one tests, and the exam-practice tools. The full topic list, with each topic linked to its revision page, is on the O Level Computer Science 2210 syllabus page.