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.
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.
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.
| Term | Meaning |
|---|---|
| Record | One complete set of related fields, such as one member's number, name and fee paid |
| Field | One item within a record, such as the member's name |
| Line of text | One record written as characters ending with a newline; the fields are separated by a delimiter such as a comma |
| Sequential access | Reading 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.
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.
| Command | Form | What it does |
|---|---|---|
| OPENFILE | OPENFILE "Data.txt" FOR READ | Connects the program to an existing file for reading |
| OPENFILE | OPENFILE "Data.txt" FOR WRITE | Creates the file for writing, losing any existing contents |
| READFILE | READFILE "Data.txt", Value | Reads the next item into Value |
| WRITEFILE | WRITEFILE "Data.txt", Value | Writes the value of Value as the next item |
| CLOSEFILE | CLOSEFILE "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.
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.
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 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 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.
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.
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.
Mark scheme — tick each point you actually made
Mark scheme — tick each point you actually made
Mark scheme — tick each point you actually made
Mark scheme — tick each point you actually made
Mark scheme — tick each point you actually made
Mark scheme — tick each point you actually made
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
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.