I am running in to an issue while reading/writing a struct having complex data specifically string. my struct looks like below.
struct MyRecord {
char name[80]
Add these two functions
std::ostream & operator << ( std::ostream & os, const MyRecord & rec ) {
os.write( rec.name, sizeof( rec.name ) );
size_t sz = rec.location.size();
os.write( & sz, iszeof( sz ) );
os.write( rec.location.c_str(), sz );
os.write( (char*) & balance, sizeof( rec.balance ) );
os.write( (char*) & account_num, sizeof( rec.account_num ) );
return os;
}
std::istream & operator >> ( std::ostream & is, MyRecord & rec ) {
is.read( rec.name, sizeof( rec.name ) );
size_t sz;
is.read( & sz, iszeof( sz ) );
rec.resize( sz );
if ( sz != 0 ) {
is.read( & rec.location[ 0 ], sz );
}
is.read( (char*) & balance, sizeof( rec.balance ) );
is.read( (char*) & account_num, sizeof( rec.account_num ) );
}
And here is a usage
ofstream outbal("balance", ios::out | ios::binary);
outbal << acc;
ifstream inbal("balance", ios::in | ios::binary);
inbal >> acc;
This is poor handmade similarity of Boost.Serialization. Indeed, it would be better to use boost, then my vehicle.