Question

So, I've been trying to automatize binary file reading and writing in C++ in the following way (basically, because when handling dynamic data things get specific):

#include <iostream>
#include <fstream>
using namespace std;

template <class Type>
void writeinto (ostream& os, const Type& obj) {
    os.write((char*)obj, sizeof(Type));
}

template <class Type>
void readfrom (istream& is, const Type& obj) {
    is.read((char*)obj, sizeof(Type));
}

int main() {
    int n = 1;
    int x;

    fstream test ("test.~ath", ios::binary | ios::out | ios::trunc);
    writeinto(test, n);
    test.close();

    test.open("test.~ath", ios::binary | ios::in);
    readfrom(test, x);
    test.close();

    cout << x;
}

And the expected output would be of '1'; this application, however, crashes before anything is show on-screen. More specifically, right when inside the writeinto function.

Could I be explained why and, if possible, a solution?

Was it helpful?

Solution

You need to take the address of the object:

#include <memory>

os.write(reinterpret_cast<char const *>(std::addressof(obj)), sizeof(Type));
//                                      ^^^^^^^^^^^^^^^^^^^

In a crunch you can also say &obj, but that's not safe in the presence of an overloaded operator&.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top