File Handling (Pseudocode)
1. File Access Modes
| Mode | Description | Behavior |
|---|---|---|
| READ | Opens an existing file to read data. | Error if file doesn't exist. |
| WRITE | Opens a file to write new data. | Overwrites existing content. Creates file if missing. |
| APPEND | Opens a file to add data to the end. | Keeps existing content. Creates file if missing. |
2. Reading from a File
To read a whole file, we use a WHILE NOT EOF() loop. EOF stands for "End of File".
DECLARE LineOfText : STRING
OPENFILE "Students.txt" FOR READ
WHILE NOT EOF("Students.txt")
READFILE "Students.txt", LineOfText
OUTPUT LineOfText
ENDWHILE
CLOSEFILE "Students.txt"
3. Writing & Appending
The syntax for Writing and Appending is identical; only the OPENFILE mode changes.
// --- WRITE MODE (OVERWRITE) ---
OPENFILE "Scores.txt" FOR WRITE
WRITEFILE "Scores.txt", "Alice, 90"
CLOSEFILE "Scores.txt"
// --- APPEND MODE (ADD TO END) ---
OPENFILE "Scores.txt" FOR APPEND
WRITEFILE "Scores.txt", "John, 85"
CLOSEFILE "Scores.txt"
⚠️ Exam Checklist:
- Did you OPENFILE before using it?
- Did you specify the MODE (READ/WRITE/APPEND)?
- Did you CLOSEFILE at the end? (This is a guaranteed 1 mark).
- When reading, did you use a variable to store the result of
READFILE?