Write pseudocode to handle text files that consist of one or more lines
10.3 Files
What is a file?
A file is a collection of data stored on a computer. Think of it as a 📚 book where each line is a page. In A‑Level CS you’ll often work with text files, which are just sequences of characters separated by line breaks.
Opening a file
Before you can read or write, you must open the file. In pseudocode:
OPEN fileName FOR mode
// mode = READ or WRITE
IF file NOT found THEN
PRINT "Error: file does not exist"
END IF
Analogy: Opening a file is like opening a diary. You choose whether to read or write in it.
Reading a file line by line
Use a loop to process each line until the end of file (EOF) is reached.
SET lineNumber = 1 WHILE NOT EOF(file) DO READ line FROM file PRINT "Line " + lineNumber + ": " + line INCREMENT lineNumber END WHILE
Here, EOF(file) is a condition that becomes true when there are no more lines to read.
Writing to a file
When writing, you usually append to the end of the file or overwrite it entirely.
OPEN fileName FOR WRITE FOR EACH item IN dataList DO WRITE item TO file END FOR CLOSE file
Analogy: Writing is like adding new chapters to a book. Each WRITE adds a new page.
Closing a file
Always close the file to free resources and ensure data is saved.
CLOSE file
Think of it as closing the diary after you’re done writing.
Common file errors
- ❌ Trying to read a file that doesn’t exist.
- ❌ Writing to a file without opening it first.
- ❌ Forgetting to close the file, which can cause data loss.
- ❌ Misusing
EOFleading to infinite loops.
File structure example
| Line No. | Content |
|---|---|
| 1 | Hello, world! |
| 2 | This is a sample file. |
Exam Tips
?? Show the full pseudocode for opening, reading, writing, and closing.
?? Explain the purpose of each step (e.g., why we check for EOF).
??
Use clear variable names like file, line, lineNumber.
?? Include error handling (e.g., file not found).
?? Remember to close the file – a common exam mistake.
Analogy recap
Think of a file as a diary 📓:
- Open the diary (OPEN).
- Read each page until the end (WHILE NOT EOF).
- Add new pages (WRITE).
- Close the diary (CLOSE).
Keeping this mental model will help you remember the flow of file operations.
Revision
Log in to practice.