9. File Handling
Cambridge IGCSE and AS & A Level sequential text files (OPENFILE, READFILE, WRITEFILE, EOF), with 9618 random-access extensions.
Files must be opened before use with OPENFILE and closed with CLOSEFILE. Sequential text files are covered by IGCSE and AS & A Level. Random-access records are an AS & A Level extension.
9.1 Text Files
Command | Description |
|---|---|
| Open for reading lines sequentially |
| Create or truncate file for writing |
| Open to append data after existing contents |
| Read next line into a STRING variable |
| Write data as a new line to the file |
| Returns TRUE if no more lines remain to be read |
| Close and flush the file |
Text File Example — Copy with Replacement
// runnable
// Text file copy demo
// Create sample input in the sandbox virtual filesystem
OPENFILE "FileA.txt" FOR WRITE
WRITEFILE "FileA.txt", "First line"
WRITEFILE "FileA.txt", ""
CLOSEFILE "FileA.txt"
DECLARE LineOfText : STRING
OPENFILE "FileA.txt" FOR READ
OPENFILE "FileB.txt" FOR WRITE
WHILE NOT EOF("FileA.txt")
READFILE "FileA.txt", LineOfText
IF LineOfText = "" THEN
WRITEFILE "FileB.txt", "----------------------------"
ELSE
WRITEFILE "FileB.txt", LineOfText
ENDIF
ENDWHILE
CLOSEFILE "FileA.txt"
CLOSEFILE "FileB.txt"
9.2 Random Files (9618)
Command | Description |
|---|---|
| Open for direct record address access |
| Move file pointer to target record number |
| Read record structure at active file pointer |
| Write record structure at active file pointer |
Random File Example
This fragment assumes the record type and an existing data file have already been created.
DECLARE Pupil : StudentRecord
DECLARE NewPupil : StudentRecord
NewPupil.LastName <- "Johnson"
NewPupil.FirstName <- "Leroy"
NewPupil.YearGroup <- 6
OPENFILE "StudentFile.Dat" FOR RANDOM
FOR Position <- 20 TO 10 STEP -1
SEEK "StudentFile.Dat", Position
GETRECORD "StudentFile.Dat", Pupil
SEEK "StudentFile.Dat", Position + 1
PUTRECORD "StudentFile.Dat", Pupil
NEXT Position
SEEK "StudentFile.Dat", 10
PUTRECORD "StudentFile.Dat", NewPupil
CLOSEFILE "StudentFile.Dat"