#include <iostream>
#include <fstream>
using namespace std;
class a{
public:
void set(int x){num = x;}
int get(){return num;}
private:
int num;
};
int main(){
ofstream o_("test.txt");
o_.close();
ofstream os("test.txt", ios::binary | **ios::app**);
a o;
o.set(1);
os.write(reinterpret_cast<char*>(&o), sizeof(a) );
// a o2;
// o.set(2);
// os.write(reinterpret_cast<char*>(&o), sizeof(a) );
os.close();
a o3,o4;
ifstream is("test.txt", ios::binary | **ios::app**);
is.read(reinterpret_cast<char*>(&o3), sizeof(a) );
// is.read(reinterpret_cast<char*>(&o4), sizeof(a) );
cout << "o3.get() => " << o3.get() << endl; *//Garbage is Printed*
// cout << "o4.get() => " << o4.get() << endl;
return 0;
}
Works fine if I do:
#include <iostream>
#include <fstream>
using namespace std;
class a{
public:
void set(int x){num = x;}
int get(){return num;}
private:
int num;
};
int main(){
ofstream o_("test.txt");
o_.close();
ofstream os("test.txt", ios::binary );
a o;
o.set(1);
os.write(reinterpret_cast<char*>(&o), sizeof(a) );
// a o2;
// o.set(2);
// os.write(reinterpret_cast<char*>(&o), sizeof(a) );
os.close();
a o3,o4;
ifstream is("test.txt", ios::binary );
is.read(reinterpret_cast<char*>(&o3), sizeof(a) );
// is.read(reinterpret_cast<char*>(&o4), sizeof(a) );
cout << "o3.get() => " << o3.get() << endl;
// cout << "o4.get() => " << o4.get() << endl;
return 0;
}