Variables and arrays store data temporarily in RAM — when a program ends, that data is lost. File handling allows data to be saved permanently to secondary storage (e.g., a hard drive) so it can be retrieved later by the same or another program.
| Operation | Keyword | Purpose |
|---|---|---|
| Open for reading | OPENFILE "name" FOR READ | Open an existing file to read from it |
| Open for writing | OPENFILE "name" FOR WRITE | Open/create file to write data (overwrites) |
| Open for append | OPENFILE "name" FOR APPEND | Open existing file to add data at the end |
| Read a line | READFILE "name", variable | Read the next line from the file into variable |
| Write a line | WRITEFILE "name", data | Write data to the file |
| Close a file | CLOSEFILE "name" | Close file when done (important!) |
| End of file check | EOF("name") | Returns TRUE when no more data to read |
OPENFILE "scores.txt" FOR WRITE WRITEFILE "scores.txt", "Alice,95" WRITEFILE "scores.txt", "Bob,82" WRITEFILE "scores.txt", "Carol,78" CLOSEFILE "scores.txt"
OPENFILE "scores.txt" FOR READ READFILE "scores.txt", line OUTPUT line // Outputs: Alice,95 CLOSEFILE "scores.txt"
OPENFILE "scores.txt" FOR READ
WHILE NOT EOF("scores.txt") DO
READFILE "scores.txt", line
OUTPUT line
ENDWHILE
CLOSEFILE "scores.txt"
OPENFILE "scores.txt" FOR APPEND WRITEFILE "scores.txt", "David,91" CLOSEFILE "scores.txt" // David's score is added at the end; previous data preserved
| Mode | Effect on existing data | Use case |
|---|---|---|
| FOR WRITE | Overwrites — all old data lost | Creating new file or replacing all data |
| FOR APPEND | Preserves old data, adds new data at end | Adding new records without deleting old ones |
4 questions · 11 marks
| Term | Definition |
|---|
10 minutes · mixed marks