Text files
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A file keeps data after the program stops
- The 2026–2028 syllabus (section 8.3) stores data in a text file.
- You open the file, read or write one item, then close it.
- This course keeps the file in memory for the one run, so you can see the result.
DECLARE LineOfText : STRING
OPENFILE "Note.txt" FOR WRITE
WRITEFILE "Note.txt", "Hello"
CLOSEFILE "Note.txt"
OPENFILE "Note.txt" FOR READ
READFILE "Note.txt", LineOfText
CLOSEFILE "Note.txt"
OUTPUT LineOfText
READ and WRITE
OPENFILE "name.txt" FOR READreads what is already there.OPENFILE "name.txt" FOR WRITEstarts a new file. Anything already in it is lost.READFILEputs the next item into a variable.WRITEFILEstores a value.CLOSEFILEwhen you have finished. A file is open in only one mode at a time.
DECLARE LineOfText : STRING
OPENFILE "FileA.txt" FOR WRITE
WRITEFILE "FileA.txt", "Saved"
CLOSEFILE "FileA.txt"
OPENFILE "FileA.txt" FOR READ
READFILE "FileA.txt", LineOfText
CLOSEFILE "FileA.txt"
OPENFILE "FileB.txt" FOR WRITE
WRITEFILE "FileB.txt", LineOfText
CLOSEFILE "FileB.txt"
OUTPUT LineOfText
Watch out
- Declare the variable before you
READFILEinto it. WRITEreplaces the file. Read it first if you still need the old text.
Common mistakes
- Open for
READorWRITE, thenREADFILEorWRITEFILE, thenCLOSEFILE. - The name of the file is a string, in double quotes.
Now you try
- Write a line, read it back, and
OUTPUTit. - Press Check answer to test it.
Write the line Hello to Note.txt, read it back into LineOfText, and output it.
Click Run to see the output here.
Store Saved in FileA.txt, read it into LineOfText, write that same text to FileB.txt, and output it.
Click Run to see the output here.