9. File Handling
Docs / Pseudocode / File Handling
CAIE 0478 & 9618 File Handling

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

OPENFILE <file> FOR READ

Open for reading lines sequentially

OPENFILE <file> FOR WRITE

Create or truncate file for writing

OPENFILE <file> FOR APPEND

Open to append data after existing contents

READFILE <file>, <var>

Read next line into a STRING variable

WRITEFILE <file>, <data>

Write data as a new line to the file

EOF(<file>)

Returns TRUE if no more lines remain to be read

CLOSEFILE <file>

Close and flush the file

Text File Example — Copy with Replacement

PSEUDOCODE Run in Sandbox
// 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

OPENFILE <file> FOR RANDOM

Open for direct record address access

SEEK <file>, <address>

Move file pointer to target record number

GETRECORD <file>, <var>

Read record structure at active file pointer

PUTRECORD <file>, <var>

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.

PSEUDOCODE
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"