[ OCR J277 ERL ]

Module 8: File Handling

Persistent Storage

When a program closes, data stored in variables is lost (RAM is volatile). To save data permanently, we write it to external files (secondary storage).

(Note: In this browser simulator, files are virtual, but the syntax is precisely what you need for the exam.)

Writing to a File

To write data, you must open the file in write mode, write lines, and crucially, close the file when done.

myFile = openWrite("scores.txt")
myFile.writeLine("Alice, 100")
myFile.writeLine("Bob, 85")
myFile.close()

Exercise: Logging Data

Open a file called "log.txt" for writing. Ask the user for their name using input, write it to the file, and then close the file.

ex1.erl

Reading from a File

To read data, we open in read mode. We often use a while loop with endOfFile() to read every line until there is nothing left.

myFile = openRead("scores.txt")

while NOT myFile.endOfFile()
    line = myFile.readLine()
    print(line)
endwhile

myFile.close()

Exercise: Virtual File Reader

The simulator has a built-in virtual file named "data.txt". Write a program to open it for reading, read all its lines using a WHILE loop, print them to the console, and close the file.

ex2.erl
← Module 7 Next Module: String Operations →