SLIDE 1
CSZone.co.uk
Click to advance · Arrow keys also work
Cambridge IGCSE 0478 · Topic 8 · 8.3

File
Handling

OPEN · READ · WRITE · APPEND · CLOSE · EOF · Text Files

CSZoneCambridge IGCSE Computer Science 0478
File Operations

Opening, Reading, Writing Files

OPENFILE: opens a file for a specific mode — READ, WRITE, or APPEND
READFILE: reads the next line from a file opened for READ
WRITEFILE: writes a line to a file opened for WRITE (overwrites) or APPEND (adds to end)
CLOSEFILE: closes the file — always do this when finished
EOF(): function returns TRUE when the end of file is reached
Writing to a File

Saving Data to a Text File

// Write mode: creates or overwrites the file
OPENFILE "scores.txt" FOR WRITE
FOR i ← 1 TO 5
INPUT score
WRITEFILE "scores.txt", score
NEXT i
CLOSEFILE "scores.txt"

// Append mode: adds to existing file
OPENFILE "scores.txt" FOR APPEND
INPUT newScore
WRITEFILE "scores.txt", newScore
CLOSEFILE "scores.txt"
WRITE creates a new file or overwrites; APPEND adds to the end of an existing file — use APPEND to keep previous data
Reading from a File

Loading Data from a Text File

// Read all lines until end of file
OPENFILE "scores.txt" FOR READ
total ← 0
count ← 0
WHILE NOT EOF("scores.txt") DO
READFILE "scores.txt", score
total ← total + score
count ← count + 1
ENDWHILE
CLOSEFILE "scores.txt"
OUTPUT "Average: ", total / count
Always use EOF() in a WHILE loop when reading — you don't know in advance how many lines the file has
Exam Practice

Have a go at this question

Cambridge IGCSE 0478 style
Describe the difference between opening a file in WRITE mode and opening it in APPEND mode. Give a situation where APPEND would be more appropriate than WRITE.
3 marks
WRITE mode creates a new file or deletes/overwrites all existing content [1]. APPEND mode adds new data to the end of the existing file without deleting the current contents [1]. APPEND is more appropriate when keeping a log — e.g. adding each day's sales to a running record without losing previous days' data [1].
Key Takeaways

What to Remember

OPENFILE / CLOSEFILE always come in pairs — always close after use
READ: read from file; WRITE: overwrite file; APPEND: add to end of existing file
Use WHILE NOT EOF("filename") DO loop to read all lines without knowing file length
Cambridge 0478 only requires text file handling — no binary or random access files