1. Opening and closing a file
A file is opened before it is used and closed when the program has finished with it. The mode says what the program may do: `READ` to read an existing file, `WRITE` for a new file, `APPEND` to add to an existing file and `RANDOM` for a random file.
A file name written in quotes is a literal string. A variable that holds the file name is written without quotes.
``` OPENFILE "Marks.txt" FOR READ OPENFILE "Report.txt" FOR WRITE CLOSEFILE "Marks.txt" CLOSEFILE "Report.txt" ```
Every file opened must be closed. Open each file in the correct mode and close it after the last statement that uses it.
Examiner insight
Worked example 15 marks
The pseudocode algorithm below copies an active accounts text file ActiveFile.txt to an archive accounts text file ArchiveFile.txt, one line at a time. Any blank lines found in the active accounts text file are replaced with the words "Account not present" in the archive accounts text file. Complete this file-handling pseudocode. Parts are missing, marked ........
``` ........ OPENFILE "ArchiveFile.txt" FOR WRITE WHILE NOT ........ READFILE "ActiveFile.txt", Account IF Account = "" THEN WRITEFILE "ArchiveFile.txt", "........" ELSE WRITEFILE "ArchiveFile.txt", ........ ENDIF ENDWHILE ........ CLOSEFILE "ArchiveFile.txt" ```
- 1
Open the file being read, in read mode: `OPENFILE "ActiveFile.txt" FOR READ` [1]
- 2
Loop until the end of the file being read: `WHILE NOT EOF("ActiveFile.txt")` [1]
- 3
Replacement text for a blank line: `WRITEFILE "ArchiveFile.txt", "Account not present"` [1]
- 4
Otherwise copy the line read: `WRITEFILE "ArchiveFile.txt", Account` [1]
- 5
Close the file that was read: `CLOSEFILE "ActiveFile.txt"` [1]