File handling and writing a complete program
Watch the whole lecture free
Make a free account to watch every lecture to the end: 5 practice questions, 2 real past-paper questions with the answers explained, the mistakes that lose marks, the full-marks tip, a one-card summary and a quick quiz.
That was the teaching part. The rest of this lecture is free with an account: 5 practice questions, 2 real past-paper questions with the answers explained, the mistakes that lose marks, the full-marks tip, a one-card summary and a quick quiz.
No password needed now: we email you a link to set one. Already have an account? Sign in, then come back to this page.
The teaching part (1 min) is free to watch. A free account opens the whole lecture: 5 practice questions, 2 real past-paper questions with the answers explained, the mistakes that lose marks, the full-marks tip, a one-card summary and a quick quiz.
What this lecture covers
- Close the program, lose the data?
- Why store data in a file?
- Five statements
- The three marks
- Writing several lines
- Reading them back
Read the transcript of the teaching part
Last time
Before we start: last time, in Selection and iteration, you learned these points. Here they are again on one card. Keep them in mind, because today builds on them.
Close the program, lose the data?
Everything a program keeps in variables and arrays disappears when it closes. To keep scores, names and settings, a program writes them to a file. The next time it runs, it reads them back. That is file handling, and it is part of the longest question in Paper 2.
Why store data in a file?
A file keeps a permanent copy, so the data is not lost when the program closes. The data can be used again, by this program or another, or moved to another computer.
Five statements
OPENFILE for WRITE creates the file, or replaces its contents. OPENFILE for READ opens an existing file. WRITEFILE writes the value as a new line. READFILE reads the next line into a variable. CLOSEFILE closes it.
The three marks
Open the file in the correct mode, write or read. Read or write the correct variable. Close the file when you have finished. Copy the file name exactly from the question, including dot t x t.
Writing several lines
Open the file for writing. Loop through the array, and write each name on its own line. Close the file. Anything that was in the file before is replaced.
Reading them back
Open the same file for reading. Each READFILE brings in the next line, one name at a time. Close the file. If the file holds Ayesha, Bilal, Chen, Dana and Eli, then position three is Chen.
How often it comes up
The whole chapter: File Handling.
Chapter 8.3: Files and the long program
- File handling and writing a complete program 6 min
Also for IGCSE Computer Science 0478
Which topics come up most in IGCSE Computer Science 0478 past papers, counted from every paper since 2004: Paper 1 topic frequency, Paper 2 topic frequency.