user3577168
user3577168

Reputation: 41

Reading object using fstream in C++

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;

Upvotes: 3

Views: 1111

Answers (1)

PSyton
PSyton

Reputation: 918

You need provide some serialization mechanism for class Produto. For example:

class Produto {
  // ...
private: 
  std::string m_str;
private: 
  friend ostream& operator<<(ostream& stream, const Produto& obj);
  friend istream& operator>>(istream& stream, Prodoto& obj)
};

ostream& operator<<(ostream& stream, const Produto& obj)
{
  // Write all data to stream.
  // ...
  stream << obj.m_str;
  return stream;
}

istream& operator>>(istream& stream, Prodoto& obj)
{
  // Read all data from strem.
  // ...
  stream >> obj.m_str;
  return stream; 
}

And then use it as below:

Produto p1(1, "Refrigerante");
ofstream serializationWriter;
// ...
serializationWriter << p1;

Produto p2;
ifstream serializationReader;
// ...
serializationReader >> p2;

For more details see overload ostream istream operator

Upvotes: 2

Related Questions