Small Steps IV — Saving and Loading

Saving numbers in binary form

Save 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

Example · example1.cpp
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.

Exercise

Save level=5, score=2300, and play_time=18.75 in binary form in game.dat.

Exercise starter · exercise1_starter.cpp
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");
}
← Previous lessonNext lesson →