Text files
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Open, then read or write
- AS topic 10.3 asks for pseudocode that handles a text file of one or more lines.
- Open the file in one mode:
READ,WRITEorAPPEND. WRITEstarts a new file and loses what was there.APPENDadds after what is there.CLOSEFILEwhen you have finished. A file is open in only one mode at a time.
OPENFILE "Note.txt" FOR WRITE
WRITEFILE "Note.txt", "Hello"
CLOSEFILE "Note.txt"
DECLARE LineOfText : STRING
OPENFILE "Note.txt" FOR READ
READFILE "Note.txt", LineOfText
CLOSEFILE "Note.txt"
OUTPUT LineOfText
EOF tells you when to stop
EOF("Note.txt")isTRUEwhen there is no further line to read.WHILE NOT EOF(...)reads every line.READFILEputs the next line into aSTRING.
OPENFILE "List.txt" FOR WRITE
WRITEFILE "List.txt", "a"
WRITEFILE "List.txt", "b"
CLOSEFILE "List.txt"
DECLARE LineOfText : STRING
OPENFILE "List.txt" FOR READ
WHILE NOT EOF("List.txt")
READFILE "List.txt", LineOfText
OUTPUT LineOfText
ENDWHILE
CLOSEFILE "List.txt"
Watch out
- Declare the string before
READFILEuses it. - Random files (
OPENFILE … FOR RANDOM) are A2. This lesson does not use them.
Common mistakes
- Read with
READFILEonly afterOPENFILE … FOR READ. WRITEreplaces the file. UseAPPENDto keep the old lines.
Now you try
- Write two lines, then read them back until
EOF.
Write Hello to Note.txt, read it back into LineOfText, and output it.
Click Run to see the output here.
Write a and b to List.txt, then output both lines using WHILE NOT EOF.
Click Run to see the output here.