Files

Computer Science AS · Data types and structures. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science AS topics

The idea

Data held in variables and arrays is stored in main memory, so it is lost when the program ends. A file on secondary storage keeps the data, so it can be used the next time the program runs or by another program.

A text file is a sequence of lines. It must be opened in a mode before it is used: READ, WRITE or APPEND. It should be closed when the program has finished with it.

A program usually does not know how many lines a file holds. The function EOF returns TRUE when there are no more lines to read. It is tested in a pre-condition loop, so that an empty file causes no read at all.

In simpler words

Variables vanish when a program stops. A file keeps data safe on a disk for next time. Before using a file you open it in one mode: read, write or append. Write wipes the old file. Append adds to the end. When reading, you rarely know how many lines there are, so you keep reading until EOF says there are none left.

An everyday comparison

A text file is like a notebook. Reading means going through it page by page from the start. Write mode is like taking a fresh, empty notebook and throwing the old one away. Append is like adding new pages after the last one. The comparison stops working because a program must open and close the file explicitly; a notebook does not need a mode.

Rules to remember

Common mistake

Opening an existing file FOR WRITE to add more data. This wipes the file. Use FOR APPEND when the old lines must be kept.

In the exam

Write the statements in this order: OPENFILE with the file name and mode, the reading or writing statements, then CLOSEFILE. Choose the mode to match the task and say why: READ for existing data, WRITE for a new file, APPEND to keep old lines. For reading an unknown number of lines, use WHILE NOT EOF(filename) DO with READFILE inside, so an empty file causes no read. Use the exact keywords from the Cambridge pseudocode guide, with the file name in quotes.

Worked example

The file scores.txt holds three lines: 40, 15 and 25. A program opens it FOR APPEND, writes the line 20 and closes it. It then opens the file FOR READ, adds every line to Total (which starts at 0) inside a WHILE NOT EOF loop, and outputs Total. What is output?

  1. APPEND keeps the three old lines and adds 20 as a fourth line.
  2. The loop reads one line on each pass, so it runs 4 times before EOF returns TRUE.
  3. Total = 40 + 15 + 25 + 20 = 100.

Answer: 100 (with FOR WRITE instead of FOR APPEND the output would be 20)

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← ArraysIntroduction to Abstract Data Types (ADT) →Take a Computer Science AS test