I'm trying to use fstream to write an object to a file and read it after but when I try to show the object read on the screen using cout the error message Segmentation fault: 11 appears. Someone could help me with this code? Thanks in advance!
Produto *p1 = new Produto(1, "Refrigerante");
cout << "Produto p1 (pre serializacao): (" << p1->codigo << ") " << p1->descricao << endl;
ofstream serializationWriter;
serializationWriter.open("myobject.dat", ios::binary);
serializationWriter.write((char *)&p1, sizeof(p1));
Produto *p2;
ifstream serializationReader;
serializationReader.open("myobject.dat", ios::binary);
serializationReader.read((char *)&p2, sizeof(p2));
cout << "Produto p2 (pos serializacao): (" << p2->codigo << ") " << p2->descricao << endl;
&p2is a pointer to a pointer, aProduto**. You probably want to makep2an instance as inProduto p2.write?serializationWriter.write((char *)&p1, sizeof(p1));The name of that variable is a misnomer. You are not "serializing" the data -- all you're doing is just taking a blob of bytes and writing it to a file. You don't serialize non-POD objects this way.p2