c++filerandombinaryfilesmt19937

How to save/retrieve mt19937 so that the sequence is repeated?


Here is my attempt

using namespace std;

int main()
{
    mt19937 mt(time(0));

    cout << mt() << endl;
    cout << "----" << endl;

    std::ofstream ofs;
    ofs.open("/path/save", ios_base::app | ifstream::binary);
    ofs << mt;
    ofs.close();

    cout << mt() << endl;
    cout << "----" << endl;

    std::ifstream ifs;
    ifs.open("/path/save", ios::in | ifstream::binary);
    ifs >> mt;
    ifs.close();

    cout << mt() << endl;

    return 0;
}

Here is a possible output

1442642936
----
1503923883
----
3268552048

I expected the two last number to be the same. Obviously, I have failed to write and/or read my mt19937. Can you help fixing this code?


Solution

  • When you open your file for writing, you're appending to an existing file. When you read it back in, you read from the start.

    Assuming you don't want to keep the existing content, change the open call to

    ofs.open("/path/save", ios_base::trunc | ifstream::binary);
    

    Using the trunc flag instead of app will truncate the existing file, so when you reopen it you're reading in the data you just wrote and not old data that was already there.