What happens to data when a program closes?
Variables and arrays usually store data in memory while a program is running.
When the program stops, that data may be lost. A text file gives the program somewhere permanent to keep important information.
File handling allows a program to save data so it is still available after the program has stopped.
Variables and arrays usually store data in memory while a program is running.
When the program stops, that data may be lost. A text file gives the program somewhere permanent to keep important information.
Before a program can use a file, it must open it. The program then reads or writes the data before closing the file safely.
First, you open the correct drawer. Next, you take information out or place information inside. Finally, you close the drawer.
The filename identifies the drawer. The data inside the file is the information being stored.
The program opens the file for reading, stores the data in a variable and then closes the file.
OPENFILE "player.txt" FOR READ READFILE "player.txt", PlayerName CLOSEFILE "player.txt" OUTPUT PlayerName
The same pattern is used for writing. The file is opened for writing, the value is stored and the file is closed.
OPENFILE "highscore.txt" FOR WRITE WRITEFILE "highscore.txt", HighScore CLOSEFILE "highscore.txt"
Data moves from the file into the program.
Data moves from the program into the file.
File-handling questions often test the correct keyword and the order of the values.
The variable and filename are reversed.
Filename first, then the value to store.
Closing the file tells the computer that the program has finished using it. It also helps ensure that written data is saved correctly.