The OPEN-USE-CLOSE pattern
Open the file, do your reading or writing, close it.
Every file operation follows the same three-step pattern.
1. OPEN the file — get a handle to it and tell the OS what you'll do (read, write or append).
OPENFILE "data.txt" FOR READ
2. USE the file — read from or write to it.
READFILE "data.txt", line // read into the variable 'line'
WRITEFILE "data.txt", value // write 'value' to the file
3. CLOSE the file — flush buffered data and release the file resource.
CLOSEFILE "data.txt"
Why CLOSEFILE matters.
- Writes are typically BUFFERED — held in RAM until the buffer fills or the file is closed. Forgetting to close can lose the unflushed data.
- The OS limits the number of files a program can have open simultaneously. Forgetting to close eventually exhausts the limit.
- Other programs may be locked out of the file until you close it.
Cambridge tip. Mark scheme penalises missing CLOSEFILE every time. Make it a habit.
- OPENFILE → operations → CLOSEFILE.
- Always close — buffered data can be lost.
- Three modes: READ, WRITE, APPEND.