Small Steps IV — Saving and Loading
Read and Write Binary Files
Read and Write Binary Files
Explore one topic in small steps. Try the examples one at a time and take a break whenever you need. Choose how many extra exercises you want to try.
Saving numbers in binary form
What you will learn
A binary file records values in a specified byte representation. Distinguish it from a text file, which stores numbers as readable characters.
Try it
void small_main()
{
File file;
file.open("save.dat", FileMode::WriteBinary);
file.write_int(3);
file.write_int(1250);
file.write_real(42.5);
file.close();
print("Binary save written");
}
Open in WriteBinary mode and write two integers and one real number in order. save.dat is not a readable sentence for a text editor.
Remember the types and order needed when reading. This mode also replaces existing contents, so use a practice file.
Reading binary data in its written order
What you will learn
To restore binary data, read it using the same types in the same order as when writing.
Try it
void small_main()
{
File file;
file.open("save.dat", FileMode::ReadBinary);
int level = file.read_int();
int score = file.read_int();
double play_time = file.read_real();
file.close();
print("Level: ", level);
print("Score: ", score);
print("Play time: ", play_time);
}
Create save.dat with the previous lesson, then run from the same source folder. read_int, read_int, and read_real restore 3, 1250, and 42.5.
Binary is not always better. Data meant for human inspection or long-term exchange needs a separately designed format and compatibility rules.
Exercise
Save level=5, score=2300, and play_time=18.75 in binary form in game.dat.
void small_main()
{
int level = 5;
int score = 2300;
double play_time = 18.75;
File file;
// Save the three values to game.dat.
}
Hint
Use WriteBinary mode, write_int twice, and write_real once.
show solution
void small_main()
{
int level = 5;
int score = 2300;
double play_time = 18.75;
File file;
file.open("game.dat", FileMode::WriteBinary);
file.write_int(level);
file.write_int(score);
file.write_real(play_time);
file.close();
print("Saved");
}
Try More (Optional)
Exercise
Save int 7 and double 3.5 in state.dat, reopen it, then read and print both values.
void small_main()
{
File file;
// write 7 and 3.5, then read them back.
}
Hint
Close between writing and reading, and use the same types and order when reading.
show solution
void small_main()
{
File file;
file.open("state.dat", FileMode::WriteBinary);
file.write_int(7);
file.write_real(3.5);
file.close();
file.open("state.dat", FileMode::ReadBinary);
int number = file.read_int();
double value = file.read_real();
file.close();
print(number);
print(value);
}