Topic 8 · Programming
File handling
Why programs store data in files, and how to open, write, read, and close a text file in pseudocode.
Lesson 7 of 7Syllabus 8.3updated October 31, 2026
Why use files?
Variables live in RAM, so their values disappear when the program ends. Storing data in a file keeps it permanently, so it can be loaded the next time the program runs, or used by another program.
Open, use, close
Every file operation follows the same pattern:
- 1Open
OPENFILE "scores.txt" FOR WRITEorFOR READ - 2Write or read
WRITEFILEsends a line to the file;READFILEreads the next line into a variable. - 3Close
CLOSEFILEsaves the file and frees it for other programs.
Watch out. Opening a file FOR WRITE replaces anything already in it.
Writing to a file
Pseudocode
DECLARE Name : STRING
OPENFILE "names.txt" FOR WRITE
INPUT Name
WRITEFILE "names.txt", Name
CLOSEFILE "names.txt"Reading from a file
Each READFILE reads the next line of the file into a variable.
Pseudocode
DECLARE FirstLine : STRING
OPENFILE "names.txt" FOR READ
READFILE "names.txt", FirstLine
OUTPUT "The first name is ", FirstLine
CLOSEFILE "names.txt"Key terms
- File
- A named collection of data stored permanently on secondary storage.
- OPENFILE
- Opens a file for reading or writing.
- READFILE / WRITEFILE
- Reads one line from, or writes one line to, an open file.
- CLOSEFILE
- Closes a file when the program has finished with it.
Check yourself
Why might a game save high scores to a file instead of a variable?Show answer
Variables are lost when the program closes; a file keeps the scores permanently for next time.
What must happen before a program can read a file?Show answer
The file must be opened with OPENFILE ... FOR READ.