File Handling
Computer ScienceΒ· 20 min read
1. Core File Lifecycle: Open, Process, Closeβ β ββββ± 5 min
All file operations follow a standard, three-step lifecycle: open the file to get access, perform your read or write operations, then close the file when done. Closing files is critical to free system resources and ensure all in-memory data is written to permanent storage.
File Mode
A setting that specifies what operations can be performed on an open file, and how the file content is interpreted.
Example:
Common modes: read, write, append, text, binary
Write CIE standard pseudocode to open a text file scores.txt in read mode, output the first line to the console, then close the file.
- 1
Declare a file handle to reference the open file, and a string variable to store the read line:
- 2
DECLARE FileHandle : FILE DECLARE FirstLine : STRING - 3
Open the file in read-only mode:
- 4
OPENFILE "scores.txt" FOR READ AS FileHandle - 5
Read the first line, output it, then close the file:
- 6
READLINE FileHandle, FirstLine OUTPUT FirstLine CLOSEFILE FileHandle
2. Text vs Binary File Modesβ β β βββ± 6 min
Text files store data as sequences of human-readable characters, encoded with standards like ASCII or UTF-8. Binary files store raw binary data directly, which is more compact and preserves the exact size of original data types.
Compare how the integer 123 is stored in a text file vs a 4-byte integer binary file.
- 1
In a text file: The integer is converted to three separate characters
'1','2','3'. This takes 3 bytes of storage, and opening the file in a text editor displays the readable text123. - 2
In a binary file: The raw 4-byte binary value of the integer 123 is stored directly. This takes 4 bytes of storage, and opening the file in a text editor shows unreadable non-printing characters.
3. Common File Operationsβ β β βββ± 7 min
Beyond basic single-line reads, you will often need to process an entire file line-by-line, append new data to an existing file, or search for a specific entry. The EOF (end of file) marker is used to detect when you have reached the end of the file content.
Write pseudocode to count the total number of lines in a text file called data.txt.
- 1
Initialize a counter to 0, and open the file for reading:
- 2
DECLARE Count : INTEGER β 0 DECLARE CurrentLine : STRING OPENFILE "data.txt" FOR READ - 3
Loop through the file, reading lines until the end of file is reached, incrementing the counter each iteration:
- 4
WHILE NOT EOF("data.txt") DO READLINE "data.txt", CurrentLine Count β Count + 1 ENDWHILE - 5
Close the file and output the final count:
- 6
CLOSEFILE "data.txt" OUTPUT "Total lines: " + Count
Test your understanding:
Which mode do you use to add new data to the end of an existing file without deleting its current content?
Read mode
Write mode
Append mode
Binary mode
Reveal answer
2 βCorrect! Append mode adds new data to the end of the file, while write mode overwrites the entire existing file.
4. File Error Handlingβ β β β ββ± 6 min
File operations often fail at runtime for common reasons: the file does not exist, you have incorrect permissions, or the storage device is full. Good programming practice requires checking for these errors and handling them gracefully instead of crashing.
File Not Found Error
A common runtime error that occurs when a program tries to open a file that does not exist in the specified path.
Modify the line counting code above to handle the case where data.txt does not exist.
- 1
After opening the file, add a check to confirm the file exists before processing:
- 2
OPENFILE "data.txt" FOR READ IF NOT FILEEXISTS "data.txt" THEN OUTPUT "Error: Input file not found" STOP ENDIF - 3
The rest of the line counting code remains unchanged, but the program outputs a clear error message to the user instead of crashing unexpectedly.
5. Common Pitfalls
Wrong move:
Forgetting to close a file after opening it
Why:
Leaves system resources allocated, and may result in data not being saved to disk
Correct move:
Always add an explicit CLOSEFILE statement after finishing work on any open file
Wrong move:
Using write mode when adding data to an existing file
Why:
Write mode overwrites the entire existing file, erasing all original content before adding new data
Correct move:
Use append mode when you want to add new data to the end of an existing file
Wrong move:
Not checking for EOF before reading the next entry
Why:
Leads to reading garbage data after the end of the file, or runtime errors during execution
Correct move:
Always wrap repeated read operations in a WHILE NOT EOF() loop to stop at the end of content
Wrong move:
Calculating text file size the same way as binary
Why:
Text files store data as variable-length characters, while binary files use fixed size per data type
Correct move:
For text files, count characters to get size; for binary, multiply number of records by fixed record size
Wrong move:
Not handling missing files in read mode
Why:
Examiners expect robust error handling, and will deduct marks for unhandled errors
Correct move:
Always add a FILEEXISTS check after opening a file in read mode
6. Quick Reference Cheatsheet
Operation | CIE Pseudocode | Common Use Case |
|---|---|---|
Open read-only | OPENFILE "f.txt" FOR READ | Read existing file |
Open write | OPENFILE "f.txt" FOR WRITE | Create/overwrite file |
Open append | OPENFILE "f.txt" FOR APPEND | Add data to end of file |
Read line | READLINE handle, lineVar | Read one line of text |
Write line | WRITELINE handle, data | Write one line of output |
Check end of file | NOT EOF(handle) | Loop through all content |
Check file exists | FILEEXISTS "filename" | Handle missing file error |
Close file | CLOSEFILE handle | Save changes, free resources |
When this came up on past exams
AI-estimated based on syllabus patterns β cross-check with official past papers for accuracy. Use only as revision-focus signals.
- 2022 Β· 12
Text file search question
- 2023 Β· 13
Binary file record write
- 2024 Β· 12
File error handling question
What's Next
File handling is a core foundational skill for both the theory and practical papers of CIE A-Level Computer Science. It is regularly tested in multiple-choice theory questions and forms a core part of most programming practical tasks, so mastering the full file lifecycle is critical for scoring full marks. Once you are comfortable with sequential file handling, you can move on to more advanced storage concepts that build on this foundation. You can also practice error handling more broadly to improve your programming robustness for exams.
