Small Steps IV — Saving and Loading
Keeping values after a program ends
Keep values after a program ends.
What you will learn
A file holds data that can remain on a storage device after the program ends. A text file records characters you can read in a text editor.
Try it
Example · example1.cpp
void small_main()
{
File file;
file.open("score.txt", FileMode::Write);
file.print("Alex");
file.print(1200);
file.close();
print("Saved score.txt");
}
Save the source before running. The program writes Alex and 1200 on separate lines in score.txt. FileMode::Write replaces existing contents. Use a practice file you created yourself.
Follow open → write → close. A relative-path file usually appears in the saved source's folder. Open it in a text editor and check the two lines.
Exercise
Save a name on one line and an age on another in profile.txt, then close the file.
Exercise starter · exercise1_starter.cpp
void small_main()
{
File file;
// Save a name and age to profile.txt.
}
Hint
Open in Write mode and use file.print twice.
show solution
void small_main()
{
File file;
file.open("profile.txt", FileMode::Write);
file.print("Alex");
file.print(12);
file.close();
print("Saved");
}