3

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;
7
  • 1
    use boost serialization! it is super awesome: boost.org/doc/libs/1_55_0/libs/serialization/doc/index.html Commented Jul 30, 2014 at 3:01
  • &p2 is a pointer to a pointer, a Produto**. You probably want to make p2 an instance as in Produto p2. Commented Jul 30, 2014 at 3:04
  • don't you also need to close the file after write? Commented Jul 30, 2014 at 3:08
  • 1
    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. Commented Jul 30, 2014 at 3:09
  • 1
    @PaulMcKenzie, it is worse. He's writing only a pointer to the file and reading the same numerical value of the pointer into p2 Commented Jul 30, 2014 at 3:26

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.