Text files are used to store data permanently. A text file consists of one or more lines of characters. Programs must be able to open, read, write, and close these files correctly.
Cambridge A-Level Computer Science uses specific pseudocode file handling commands which must be followed exactly in exams.
| Command | Purpose |
|---|---|
| OPENFILE filename FOR READ | Open file for reading |
| OPENFILE filename FOR WRITE | Open file for writing (overwrites file) |
| OPENFILE filename FOR APPEND | Open file to add data to end |
| READFILE filename, variable | Read one line from file |
| WRITEFILE filename, data | Write data to file |
| CLOSEFILE filename | Close file after use |
| EOF(filename) | Checks if end of file reached |
When a file has multiple lines, a loop must be used to read each line until the end of the file.
Example text file Names.txt:
Ali
Mary
John
Pseudocode:
OPENFILE "Names.txt" FOR READ
WHILE NOT EOF("Names.txt")
READFILE "Names.txt", Name
OUTPUT Name
ENDWHILE
CLOSEFILE "Names.txt"
Explanation:
Example pseudocode:
OPENFILE "Names.txt" FOR WRITE
WRITEFILE "Names.txt", "Ali"
WRITEFILE "Names.txt", "Mary"
WRITEFILE "Names.txt", "John"
CLOSEFILE "Names.txt"
Each WRITEFILE statement creates a new line in the file.
APPEND adds new data without deleting existing data.
OPENFILE "Names.txt" FOR APPEND
WRITEFILE "Names.txt", "David"
CLOSEFILE "Names.txt"
Example:
OPENFILE "Names.txt" FOR READ
Count ← 0
WHILE NOT EOF("Names.txt")
READFILE "Names.txt", Name
Count ← Count + 1
ENDWHILE
CLOSEFILE "Names.txt"
OUTPUT Count
This counts how many lines are in the file.
Example:
OPENFILE "Names.txt" FOR READ
Found ← FALSE
INPUT SearchName
WHILE NOT EOF("Names.txt")
READFILE "Names.txt", Name
IF Name = SearchName THEN
Found ← TRUE
ENDIF
ENDWHILE
CLOSEFILE "Names.txt"
IF Found = TRUE THEN
OUTPUT "Name found"
ELSE
OUTPUT "Name not found"
ENDIF
OPENFILE "Names.txt" FOR APPEND
INPUT Name
WRITEFILE "Names.txt", Name
CLOSEFILE "Names.txt"
Mistake:
READFILE "Names.txt", Name
READFILE "Names.txt", Name
READFILE "Names.txt", Name
Correct method:
WHILE NOT EOF("Names.txt")
READFILE "Names.txt", Name
ENDWHILE
1. Write pseudocode to read and display all lines from a text file.
2. Write pseudocode to count number of lines in a file.
3. Write pseudocode to add a new line to a file.
4. Write pseudocode to search for a name in a file.
5. Explain why CLOSEFILE must be used.