1

Hello guys I am new to c++ programming I have saved struct in binary file.. But when try to read it application is crashing Here is my code

struct Person
{
    string name;
    int age;

};
void main()
{
    Person p;
    ifstream is("person.data",ios::binary);
    is.read((char*)&p,sizeof(p));


}
1
  • 2
    You need to have a look into serialization. You cannot save complex classes as binary images to a file. Commented Feb 24, 2015 at 19:24

1 Answer 1

4

You're using sizeof(p).

The string class is of variable length. This means it is essentially a struct with a pointer in it to some other characters in the heap. Attempting to read the string in via struct won't work. You have to put all the characters in the struct itself, or it will just read in a (now-dead) pointer to somewhere in the heap and likely cause a segmentation fault.

Try this:

struct Person
{
    char name[40];
    int age;

};
void main()
{
    Person p;
    ifstream is("person.data",ios::binary);
    is.read((char*)&p,sizeof(p));
}

Then use c string functions instead of C++ ones found in cstring or string.h.

Honestly, though, you may want to listen to @πάντα ῥεῖ . You're trying to serialize C structs. Reading data in via struct is a very "C" thing to do, but you're mixing "C++" classes into that. The two paradigms don't mix very well. BOOST has a serialization library, if you really want to serialize C++ classes I would start there.

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.