Small Steps IV — Saving and Loading
Reading values back from a file
Read values back from a file.
What you will learn
Opening a saved file retrieves values from a previous run. A path identifies the file's location.
Try it
Example · example2.cpp
void small_main()
{
File file;
file.open("score.txt");
String name = file.input();
int score = file.input_int();
file.close();
print(name, "'s score: ", score);
}
First create score.txt with the previous lesson. Save this source in the same folder to read the same file.
open's default mode is reading. Input reads the first line as a string; input_int reads the second as an integer. Check for Alex's score: 1200. If an error occurs, check the file location and line contents.
Exercise
Save 950 in highscore.txt, reopen it, read it as an int, and print it.
Exercise starter · exercise2_starter.cpp
void small_main()
{
File file;
// Save 950, close the file, then read it back.
}
Hint
After write and close, open the file again and use input_int().
show solution
void small_main()
{
File file;
file.open("highscore.txt", FileMode::Write);
file.print(950);
file.close();
file.open("highscore.txt");
int score = file.input_int();
file.close();
print("High score: ", score);
}