File Handling
Programming · 4 question types
Why Files Are Used
A running program holds all its data in RAM, which is volatile: the moment the program ends or the computer is turned off, every variable disappears (topic 9). For data to survive across program runs, it must be saved to secondary storage as a .
Files are how programs:
- Remember user data between sessions (a saved game, a contact list, a logged-in session).
- Read input data prepared elsewhere (a list of student names, a configuration file, a CSV export).
- Write reports and logs that other programs or people can read later.
- Share data between programs that do not run at the same time.
The focus here is on text files: simple human-readable files made of lines of text.
Why a program stores data in a file
Question: Explain or outline why it is useful for a program to store its data in a file (2 marks).
Asked in 2 of the 17 papers. Make two different points. A file is kept on non-volatile storage, so the data is permanent and is not lost when the program ends or the computer is switched off. Because it is kept, the data can be retrieved and used again later, by the same program or by a different one. One scheme also credits the idea that a file can be moved to another computer.
Writing that the data is permanent and that it will not be lost makes one point twice, and earns one mark: make the reuse point your second.
The basic life cycle
Working with a file always follows the same four-step pattern:
- Open the file in the appropriate mode (read or write).
- Read lines from it or write lines into it.
- Continue until the work is done.
- Close the file.
Skipping the close step is one of the most common bugs in file-handling code. The next section explains why.