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.

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.

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