Small Steps IV — Saving and Loading

Reading binary data in its written order

Read 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

Example · example2.cpp
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 int 7 and double 3.5 in state.dat, reopen it, then read and print both values.

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