Skip to content
Cambridge AS & A Level9618

Files

Computer Science 9618 Chapter Notes

Last updated November 2026

ShareWhatsAppPost

Files notes as a printable PDF.

Read online free. Download a watermarked copy with a free account.

Read the notes

The full Files notes as text: skim, search, and jump between subtopics.

~17 min read

1. Why files are needed

An array is temporary storage. When the program ends or the computer is switched off, the data in it is lost.

Data written to a file is retained after the computer is switched off, so it is stored permanently and is non-volatile.

This is why a program can write its arrays to a file at the end of the day and read them back at the start of the next. The data is then only entered once.

Examiner insight

“Many candidates made little or no reference to the scenario and simply described how arrays represented temporary storage while file storage was permanent.” “A number of answers suggested that data would be ‘easier to process’ when stored in a file, which did not gain credit.”

Worked example 13 marks

A concert venue uses a program to calculate admission prices and store information about ticket sales.

A number of arrays are used to store data. The computer is switched off overnight and data has to be input again at the start of each day before any tickets can be sold. This process is very time consuming.

(i) Explain how the program could use text files to speed up the process.

(ii) State the characteristic of text files that allow them to be used as explained in part (i).

  1. 1

    (i) data from the arrays is written to the files at the end of the day / before the computer is switched off [1]

  2. 2

    (i) data is read from the files at the start of the next day and stored in the arrays [1]

  3. 3

    (ii) the data is retained after the computer is switched off // stored permanently // non-volatile storage [1]

2. Opening, file modes and closing

A file must be opened before it is used, in one of three modes, and closed when the program has finished with it. The file name is the first item in every file statement that follows.

READ mode is for reading lines. WRITE mode replaces the existing contents, so existing data is overwritten. APPEND mode adds new lines to the end and keeps what is there.

Name the mode in the answer. Open the same file once, before any loop, and close it once, after the loop.

Examiner insight

“Some answers referred to WRITE mode being used to create a new file but did not make it clear that existing data would be over-written.” “A number of candidates who attempted this question lost a mark for not putting quotes around the file name when writing the instruction to open and/or close the file.”

Worked example 15 marks

An algorithm will process data from a test taken by a group of students. The algorithm will prompt and input the name and test mark for each of the 35 students.

The algorithm will add the names of all the students with a test mark of less than 20 to an existing text file Support_List.txt, which already contains data from other group tests.

Describe the steps that the algorithm should perform.

Do not include pseudocode statements in your answer.

  1. 1

    open the file in APPEND mode (and subsequently close it) [1]

  2. 2

    prompt and input a student name and mark [1]

  3. 3

    if the mark is greater than or equal to 20, jump to the repeat step [1]

  4. 4

    write only the name to the file [1]

  5. 5

    repeat for 35 students [1]

3. Reading a file line by line

`READFILE` takes the file name and a variable, and reads the next line into the variable. The function `EOF(File)` returns a Boolean: TRUE when there are no more lines to read.

To read a whole file, use a conditional loop that tests `EOF` before each read. This also copes with an empty file. Close the file after the loop.

``` OPENFILE ThisFile FOR READ WHILE NOT EOF(ThisFile) READFILE ThisFile, ThisLine OUTPUT ThisLine ENDWHILE CLOSEFILE ThisFile ```

Process every line the file holds. A blank line is still a line.

Examiner insight

“Another mistake was to compare EOF(filename) with an empty string rather than a Boolean value.” “Some lost this mark as they chose to skip blank lines, which was not in the question.”

Worked example 15 marks

A procedure Preview() will:

• take the name of a text file as a parameter

• output a warning message if the file is empty

• otherwise output the first five lines from the file (or as many lines as there are in the file if this number is less than five).

Write pseudocode for the procedure Preview().

  1. 1

    procedure heading (including the parameter) and ending [1]

  2. 2

    file `OPENFILE` and subsequently `CLOSEFILE` [1]

  3. 3

    check if the file is empty and output a warning message if it is [1]

  4. 4

    a conditional loop [1]

  5. 5

    output the line (including blank lines) and read the next line in the loop [1]

  6. 6

    ``` PROCEDURE Preview(ThisFile : STRING) DECLARE LineNum : INTEGER DECLARE ThisLine : STRING OPENFILE ThisFile FOR READ IF EOF(ThisFile) THEN OUTPUT "Warning Message" ELSE LineNum ← 1 WHILE LineNum < 6 AND NOT EOF(ThisFile) READFILE ThisFile, ThisLine OUTPUT ThisLine LineNum ← LineNum + 1 ENDWHILE ENDIF CLOSEFILE ThisFile ENDPROCEDURE ```

4. Writing lines to a file

`WRITEFILE` takes two items: the file name and the data. Each `WRITEFILE` statement writes one line to the file.

``` OPENFILE NewFile FOR WRITE WRITEFILE NewFile, "Hello" CLOSEFILE NewFile ```

Join pieces of text with the `&` operator. A comma only separates the file name from the data. `CLOSEFILE` also needs the file name.

Examiner insight

“Very many instances of CLOSEFILE appeared without a filename. The use of CREATEFILE was common although this is not mentioned in the Pseudocode Guide for Teachers.” “A very common mistake was for the WRITEFILE command to have just one parameter (rather than <filename>,<data>) and this was exacerbated by the frequent use of a comma instead of the correct & operator to concatenate the filename with the suffix.”

Worked example 16 marks

A procedure CreateFiles() will take two parameters:

• a string representing a file name

• an integer representing the number of files to be created.

The procedure will create the number of text files specified.

Each file is given a different name. Each file name is formed by concatenating the file name with a suffix based on the file number. The suffix is always three characters.

For example, the call CreateFiles("TestData", 3) would result in the creation of the three files, TestData.001, TestData.002 and TestData.003.

Each file will contain a single line. For example, file TestData.002 would contain the string:

This is File TestData.002

Write pseudocode for CreateFiles().

Assume both parameters are valid and that the integer value is between 1 and 999, inclusive.

  1. 1

    procedure heading, including parameters, and ending [1]

  2. 2

    a loop for NumFiles iterations [1]

  3. 3

    attempt to create the filename suffix using `NUM_TO_STR()` in a loop [1]

  4. 4

    the completely correct filename, with the dot [1]

  5. 5

    `OPENFILE` in WRITE mode and subsequent `CLOSEFILE`, in the loop [1]

  6. 6

    write the first line to the file, in the loop [1]

  7. 7

    ``` PROCEDURE CreateFiles(NameRoot : STRING, NumFiles : INTEGER) DECLARE FileName, Suffix : STRING DECLARE Count : INTEGER FOR Count ← 1 TO NumFiles Suffix ← NUM_TO_STR(Count) WHILE LENGTH(Suffix) <> 3 Suffix ← "0" & Suffix ENDWHILE FileName ← NameRoot & "." & Suffix OPENFILE FileName FOR WRITE WRITEFILE FileName, "This is File " & FileName CLOSEFILE FileName NEXT Count ENDPROCEDURE ```

5. Several items in a text file

A text file holds only text, in lines. Data with several items for one booking can be stored in two ways.

The items are combined into a single string and saved as a single line, with a special separator character between them. Or each item is saved on a line of its own. In both, a number is first converted to a string.

The separator must not appear in any of the data items, or the line cannot be split correctly.

Examiner insight

“Many answers attempted to store the data as a record in the file, although the question specified a text file was to be used.” “There were few references to the need to convert all data items to strings.”

Worked example 12 marks

Information about ticket sales will be stored as a booking. The booking requires the following data:

• name of person booking

• number of people in the group (for example a family ticket or a school party)

• event type.

Suggest how data relating to each booking may be stored in a text file.

  1. 1

    data items are combined to form a single string / saved as a single line in the file [1]

  2. 2

    data items are separated by a special character // each data item is a fixed length [1]

6. Describing a file algorithm in steps

Some questions ask you to describe an algorithm and not to use pseudocode statements. Write steps that could be turned directly into code.

A good description names the file and its mode, reads a line in a loop, says what is done to each line, and says when the loop repeats: for a fixed number of times or until the end of the file.

Use the names in the question. Examiners found steps that only repeat phrases from the question too vague.

Examiner insight

“Many answers did not give a viable description of the required steps for this simple algorithm.” “Steps were often vague and frequently simply repeated phrases from the question.”

Worked example 15 marks

A text file Sales.txt stores strings representing the number of items sold.

The file contains 52 lines, each representing the number of items sold in each week of the year.

The owner requires a module to output all week numbers where the number of items sold is greater than 500.

Describe an algorithm that produces the required module.

Do not include pseudocode statements in your answer.

The example shows that 502 items were sold in week 2.

File line numberFile data
1"350"
2"502"
3"434"
……
49"492"
50"872"
51"772"
52"201"
  1. 1

    open the file (Sales.txt) in read mode and subsequently close [1]

  2. 2

    read a line from the text file [1]

  3. 3

    convert the line read (a string) to a number [1]

  4. 4

    if the number is greater than 500, output the week number [1]

  5. 5

    increment the week number (it must have been initialised) [1]

  6. 6

    repeat from the read step 52 times // until end of file (a sixth point, with a maximum of 5)

Recap

  • An array is temporary storage. A file keeps data after the computer is switched off.
  • Open a file in READ, WRITE or APPEND mode, once, before the loop. Close it after the loop.
  • WRITE overwrites existing data. APPEND adds to the end.
  • Read with a conditional loop: WHILE NOT EOF(File), then READFILE File, Variable.
  • WRITEFILE needs the file name and the data. Join text with &, not a comma.
  • A file name in quotes is a literal name. A parameter name is never in quotes.
  • Several items on one line need a separator that is not in the data, and numbers converted to strings.

End-of-chapter exercise

Test yourself on the whole chapter. Work through these before moving on.

  1. A program stores the day's sales in an array. The computer is switched off overnight. (a) State what happens to the data in the array. (b) State the characteristic of a text file that solves this problem.2 marks
    Answer
    1. (a)
    2. The data is lost, because an array is temporary storage.
    3. (b)
    4. Data in a file is retained after the computer is switched off (non-volatile).

    Trap: ‘Easier to process’ earns nothing. The credited point is that file data is kept when the computer is switched off.

  2. State the file mode needed for each task. (a) Output every line of Notes.txt. (b) Replace everything in Notes.txt with new lines.2 marks
    Answer
    1. (a)
    2. READ.
    3. (b)
    4. WRITE.

    Trap: APPEND keeps the old lines, so it does not replace them.

  3. Write three pseudocode statements that open the file Names.txt for reading, read one line into the variable FirstName, and close the file.3 marks
    Answer
    1. `OPENFILE "Names.txt" FOR READ`
    2. `READFILE "Names.txt", FirstName`
    3. `CLOSEFILE "Names.txt"`

    Trap: READFILE needs the file name as well as the variable. A literal file name is in quotes.

  4. The file Colours.txt holds three lines: red, green, blue. State the output of this code. ``` OPENFILE "Colours.txt" FOR READ Count ← 0 WHILE NOT EOF("Colours.txt") READFILE "Colours.txt", Item Count ← Count + 1 OUTPUT Item ENDWHILE CLOSEFILE "Colours.txt" OUTPUT Count ```2 marks
    Answer
    1. The loop body runs once for each line: red, green, blue are output in turn.
    2. After the loop, Count is 3, so the last output is 3.

    Trap: EOF is tested before each read, so the loop runs three times, not four.

  5. A club stores each member's name and number of years in the club in a text file, one member on each line. Names can contain spaces and commas, for example "Lee, Ann". Suggest how the data for one member may be stored on a line.3 marks
    Answer
    1. Combine the two items into a single string, saved as one line.
    2. Convert the number of years to a string first.
    3. Separate the items with a character that does not occur in the data, such as #. For example: `Lee, Ann#4`.

    Trap: A comma looks natural, but it occurs in the names, so the line could not be split correctly.

  6. The file Out.txt does not exist before this code is run. ``` OPENFILE "Out.txt" FOR WRITE FOR Index ← 1 TO 3 WRITEFILE "Out.txt", "Item" & NUM_TO_STR(Index) NEXT Index CLOSEFILE "Out.txt" ``` (a) State the contents of Out.txt after the code runs once. (b) The word WRITE is changed to APPEND and the code is run once more. State the contents of Out.txt.3 marks
    Answer
    1. (a)
    2. Three lines: Item1, Item2, Item3.
    3. (b)
    4. The three lines already there are kept, so the file holds six lines: Item1, Item2, Item3, Item1, Item2, Item3.

    Trap: In WRITE mode a second run would overwrite the first three lines. APPEND keeps them.

  7. A program asks a user for the name of a new member and adds it to the end of the text file Members.txt, which already holds the names of other members. Describe the steps the algorithm should perform. Do not include pseudocode statements in your answer.4 marks
    Answer
    1. Prompt for and input the name.
    2. Open Members.txt in append mode.
    3. Write the name to the file.
    4. Close the file.

    Trap: WRITE mode would overwrite the names already in the file. Not naming the mode loses a mark.

  8. A procedure CountLines() takes the name of a text file as a parameter and outputs the number of lines in the file. Write pseudocode for CountLines().5 marks
    Answer
    1. Procedure header with the parameter, and ENDPROCEDURE.
    2. Total declared and set to 0 before the loop.
    3. `OPENFILE ThisFile FOR READ` before the loop and `CLOSEFILE ThisFile` after it.
    4. Conditional loop `WHILE NOT EOF(ThisFile)`, with `READFILE ThisFile, ThisLine` and Total increased by 1 inside it.
    5. `OUTPUT Total` after the loop.
    6. ``` PROCEDURE CountLines(ThisFile : STRING) DECLARE ThisLine : STRING DECLARE Total : INTEGER Total ← 0 OPENFILE ThisFile FOR READ WHILE NOT EOF(ThisFile) READFILE ThisFile, ThisLine Total ← Total + 1 ENDWHILE CLOSEFILE ThisFile OUTPUT Total ENDPROCEDURE ```

    Trap: Total must be set to 0 first. The parameter ThisFile is never in quotes, and EOF needs the file name.

  9. A text file Parts.txt holds one line for each part a garage sells. Each line starts with a 5-character part code, followed by the part's description, for example "AB120Brake pad". The lines are in ascending order of part code. A function FindPart() takes a part code as a string parameter. It returns the description of that part, or an empty string if the code is not in the file. To be efficient, it must stop reading the file as soon as the part is found or a part code greater than the parameter is read. Write pseudocode for FindPart().8 marks
    Answer
    1. Function header with the parameter and RETURNS STRING, and ENDFUNCTION.
    2. `OPENFILE "Parts.txt" FOR READ` before the loop and `CLOSEFILE "Parts.txt"` after it, the literal name in quotes.
    3. Conditional loop until `EOF("Parts.txt")`...
    4. ... or the part is found ...
    5. ... or a part code greater than the parameter is read (a flag set in either case).
    6. Read a line and extract its code with `LEFT(ThisLine, 5)`, in the loop.
    7. When the codes match, extract the description with `RIGHT(ThisLine, LENGTH(ThisLine) - 5)`.
    8. Description set to "" before the loop and returned after the file is closed.
    9. ``` FUNCTION FindPart(Code : STRING) RETURNS STRING DECLARE ThisLine, ThisCode, Description : STRING DECLARE Finished : BOOLEAN Description ← "" Finished ← FALSE OPENFILE "Parts.txt" FOR READ WHILE NOT EOF("Parts.txt") AND Finished = FALSE READFILE "Parts.txt", ThisLine ThisCode ← LEFT(ThisLine, 5) IF ThisCode = Code THEN Description ← RIGHT(ThisLine, LENGTH(ThisLine) - 5) Finished ← TRUE ELSE IF ThisCode > Code THEN Finished ← TRUE ENDIF ENDIF ENDWHILE CLOSEFILE "Parts.txt" RETURN Description ENDFUNCTION ```

    Trap: Examiners found very few loops that stopped when the item was found or passed, and a RETURN inside the loop skips the CLOSEFILE.

  10. A text file Guests.txt holds one guest name on each line, in ascending alphabetical order. Two names are compared with < and >. A procedure AddGuest() takes a new name as a string parameter. The name is not already in the file. The procedure creates a new file NewGuests.txt that holds every name from Guests.txt with the new name inserted in its correct place. The new name may belong before the first name, between two names, or after the last name. Write pseudocode for AddGuest().8 marks
    Answer
    1. Procedure header with the parameter, and ENDPROCEDURE.
    2. Guests.txt opened in READ mode and NewGuests.txt in WRITE mode, names in quotes.
    3. Both files closed after the loop.
    4. Loop until `EOF("Guests.txt")`, the file being read, and read a line in the loop.
    5. Before the first name greater than the new name, write the new name ...
    6. ... once only, using a flag.
    7. Write the line just read to NewGuests.txt in every pass of the loop.
    8. After the loop, write the new name if it has not been written.
    9. ``` PROCEDURE AddGuest(NewName : STRING) DECLARE ThisLine : STRING DECLARE Inserted : BOOLEAN Inserted ← FALSE OPENFILE "Guests.txt" FOR READ OPENFILE "NewGuests.txt" FOR WRITE WHILE NOT EOF("Guests.txt") READFILE "Guests.txt", ThisLine IF Inserted = FALSE AND NewName < ThisLine THEN WRITEFILE "NewGuests.txt", NewName Inserted ← TRUE ENDIF WRITEFILE "NewGuests.txt", ThisLine ENDWHILE IF Inserted = FALSE THEN WRITEFILE "NewGuests.txt", NewName ENDIF CLOSEFILE "Guests.txt" CLOSEFILE "NewGuests.txt" ENDPROCEDURE ```

    Trap: Examiners reported answers that wrote the new name but not the line just read, stopped copying after the insertion, or tested EOF() on the file open for WRITE.

Say this, not that

Wording that loses the mark, against the wording the mark scheme credits.

Loses the markGets the mark
‘the data is written to the file’, with no mention of the scenariodata is written from the arrays to the file at the end of the day and read back at the start of the next
data in a file is ‘easier to process’data in a file is non-volatile, so it need not be re-entered the next time the program is run
WRITE mode is used to create a new fileWRITE mode would overwrite existing data, so use APPEND to add to a file
`OPENFILE "ThisFile" FOR READ` when ThisFile is the parameter`OPENFILE ThisFile FOR READ`: the parameter name, without quotes

Frequently asked questions

Why does a program need to write its data to a file?
An array is temporary storage, and its data is lost when the program ends or the computer is switched off. Data written to a file is retained after the computer is switched off, because file storage is non-volatile. A program can write its arrays to a file at the end of the day and read them back at the start of the next, so the data is entered only once.
What are the file modes READ, WRITE and APPEND?
READ mode opens a file for reading lines. WRITE mode replaces the existing contents, so existing data is overwritten. APPEND mode adds new lines to the end and keeps what is there. Open the file once, before any loop, and close it once, after the loop.
How do you read a text file line by line in pseudocode?
Use a conditional loop, WHILE NOT EOF(ThisFile), and inside it READFILE ThisFile, ThisLine followed by OUTPUT ThisLine. EOF returns TRUE when there are no more lines, and the test runs before each read, so an empty file is handled. Close the file after the loop. A blank line is still a line.
How do I store several items for one booking in a text file?
Combine the items into a single string and save it as one line, with a special separator character between them, such as #. Convert any number to a string first. The separator must not appear in any of the data items, or the line cannot be split correctly. Alternatively, save each item on a line of its own.
How does WRITEFILE work, and why use & instead of a comma?
WRITEFILE takes the file name and the data, and each statement writes one line. A comma only separates the file name from the data. Join pieces of text with the & operator, for example to build a file name from a root and a suffix. CLOSEFILE also needs the file name.
Why do my earlier lines disappear when I add data to a text file?
The file was probably opened in WRITE mode. WRITE replaces the existing contents, so existing data is overwritten. Use APPEND mode to add new lines to the end of the file and keep what is already there. Naming the mode in your steps also matters, and leaving it out loses a mark.

Free notes are just the start.

Unlock every Workbook and Chapter at a Glance, and generate your own worksheets and predicted papers.

Explore plans

Related chapters