File handling: OPENFILE, READFILE and WRITEFILE
Variables are lost when a program ends. Storing data in a file keeps it, so it can be used the next time the program runs, or by a different program.
Why use files
- Data is stored permanently, so it isn’t lost when the program closes.
- The data can be read again later, or by another program.
- Large amounts of data don’t have to be typed in every time.
Writing and reading
A file is opened in a mode: WRITE to create it (replacing anything already in it) or READ to take data from it. WRITEFILE puts a line into the file, READFILE takes the next line into a variable, and CLOSEFILE closes it when you’ve finished.
DECLARE Title : STRING
OUTPUT "Enter a song title"
INPUT Title
OPENFILE "Songs.txt" FOR WRITE
WRITEFILE "Songs.txt", Title
CLOSEFILE "Songs.txt"
OPENFILE "Songs.txt" FOR READ
READFILE "Songs.txt", Title
CLOSEFILE "Songs.txt"
OUTPUT "Saved:", TitleWhere marks go
- Forgetting to open the file, or opening it in the wrong mode.
- Not closing the file afterwards.
- Opening for WRITE when the old contents should be kept, since WRITE replaces them.
- Leaving out the file name in READFILE or WRITEFILE.
- Saying files are used “to save data” without saying the data is kept after the program closes.
Try a question
3 MARKS · MARKED ON THIS PAGEA music app saves the title of the song a user has just added so it is not lost. Write a program in pseudocode that: - declares the variables Title and SavedTitle as STRING - inputs a song title into Title - opens the file "playlist.txt" for writing, writes Title to the file and closes the file - opens "playlist.txt" again for reading, reads the line from the file into SavedTitle and closes the file - outputs the message Saved: followed by SavedTitle, using OUTPUT "Saved: ", SavedTitle Do not output any other messages or prompts.
solutionPseudocode
Loading...
Type your answer first.