File Handling · Cambridge syllabus 8.3 · Lesson 1 of 2
Files
Files keep data beyond one program run. A program’s ordinary variables are temporary unless their values are saved. Choose a representation that can be read back consistently and decide what should happen when a file is missing or empty.
By the end, you can
- Understand why programs store data in files.
- Distinguish temporary data from persistent data.
- Identify situations where file storage is appropriate.
Purpose of files
Everything a program holds in variables and arrays is in RAM, and RAM is volatile: when the program ends or the power goes, it is gone. A file is data written to secondary storage, where it survives both.
That is the distinction to be clear about. Temporary data exists only for the run — a loop counter, a running total, the contents of an array being sorted. Persistent data must outlive the run: the high scores, the customer records, the settings, the report that was generated.
Files are used whenever a program must remember between runs, whenever the data is too large to hold in memory at once, whenever the output is for another program or another person, and whenever a record must be kept of what happened.
A text file holds characters, is readable in any editor, and is the kind used in the syllabus. Data is usually written a line at a time, and separated within a line by a chosen character such as a comma — which is what a CSV file is, and why a spreadsheet can open one.
The pattern of a program that uses a file is: open it once, read what is needed into variables or an array, work on the data in memory, write the results back, and close it. Reading or writing many lines is done with a loop, one READFILE or WRITEFILE for each line.
Worth remembering
- RAM is volatile; a file on secondary storage persists between runs.
- Temporary data lives for one run; persistent data must outlive it.
- Open once, read into variables or an array, work in memory, write back, close.
Worked example
A quiz program can save scores to a file so a later run can display earlier results.
Practice
Warm-up · not marked
Check your understanding
Answer in your own words, then compare with the worked answer. Nothing here is saved or scored.
Worked answer
The file can retain them after the program ends, while working variables normally do not.
Check your method, units and explanation against it.
Marked practice
Set 1 of 4 · easiest first · Checked as you go, with the worked answer. Sign in or create a free account to save your progress.