File handling Cambridge IGCSE Computer Science revision
Not started
Learn it
In plain words
Everything a program holds in its variables disappears the moment it stops. If the data is needed again tomorrow, the program must write it to a file on secondary storage, and read it back when it next runs.
5 things to know
- Data is stored in a file so that it is not lost when the program ends. It can be used again by the same program, or by another one.
- A file must be opened before it is used: OPENFILE "Scores.txt" FOR READ, or OPENFILE "Scores.txt" FOR WRITE.
- READFILE "Scores.txt", Line reads one line of text from the file into the variable Line.
- WRITEFILE "Scores.txt", Line writes the contents of the variable Line to the file.
- CLOSEFILE "Scores.txt" closes the file when the program has finished with it.
Worked example
A game must save the player's high score so that it is still there the next time the game is played. Describe the pseudocode steps.
- Open the file for writing: OPENFILE "HighScore.txt" FOR WRITE.
- Write the value: WRITEFILE "HighScore.txt", HighScore.
- Close the file: CLOSEFILE "HighScore.txt".
Tips and tricks
- The order is always open, then read or write, then close. A file opened FOR READ cannot be written to.
- "So that the data is not lost when the program ends" is the reason for using a file. Variables are held in RAM.
It lands in your notebook with its questions as flashcards.
File handling: 5 questions and answers
These are the quiz’s questions. Do the quiz first, then come back here for the ones that got you.
Why is data stored in a file?
Variables are lost when the program stops.
Which statement must come before reading from a file?
A file has to be opened before it can be used.
What does READFILE "Data.txt", Line do?
The data moves from the file into the variable.
What does WRITEFILE "Data.txt", Line do?
The data moves from the variable into the file.
What should be done when a program has finished using a file?
CLOSEFILE "Data.txt".
Quiz
5 questions
Tap an answer and you’ll see straight away whether it’s right, and why.
Worksheet
2 questions, 5 marks. Write your answers on paper, then check them.
File handling
Cambridge IGCSE Computer Science 0478 · 5 marks · papermunch.org
Name ______________________________ Date ______________
Explain why a program might store data in a file.[2]
Show answerHide answer
Data held in variables is lost when the program ends. Data in a file is kept, so it can be used again later.
Write pseudocode to read one line from the file "Names.txt" into the variable Name.[3]
Show answerHide answer
OPENFILE "Names.txt" FOR READ. READFILE "Names.txt", Name. CLOSEFILE "Names.txt".
Answers: File handling
- 1. Data held in variables is lost when the program ends. Data in a file is kept, so it can be used again later.
- 2. OPENFILE "Names.txt" FOR READ. READFILE "Names.txt", Name. CLOSEFILE "Names.txt".



