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?
You need to take the address of the object:
In a crunch you can also say
&obj, but that’s not safe in the presence of an overloadedoperator&.