1

I learn how to store object class in a file and how to get it back. But I don't know why this program crashes?

#include <iostream>
#include <fstream>
using namespace std;
class person{
public:
    string wife , son , mother;
    int brothers_num , sisters_num;
};

int main()
{
    person Ahmed;
    Ahmed.wife = "Aya";
    Ahmed.son = "Badr";
    Ahmed.mother = "Fatma";
    Ahmed.brothers_num = 2;
    Ahmed.sisters_num = 2;
    fstream new_file;
    new_file.open("database.txt" , ios::out );
    if(new_file.fail()){
        cout<<"can't open the files\n";
    }
    new_file.write((char*)&Ahmed , sizeof(Ahmed));
    new_file.close();

    person Khaled;
    new_file.open("database.txt" , ios::in);
    new_file.read((char*)&Khaled , sizeof(Khaled));
    new_file.close();

    cout<<Khaled.wife;

    return 0;
}

I write any thing as the website wants that

6
  • Be aware that this is not a safe way to serialize binary objects. Your object will have different size in debug build and release build, and also in 32 bit and 64 bit, giving you at least 4 different binary formats. Oct 14, 2022 at 19:21
  • Another thing to consider: you can store e.g. 2kB in a string. sizeof(person) gives you values between 80 and 128 bytes (see comment before) - but how will the 2kB string be stored in that number of bytes? Oct 14, 2022 at 19:27
  • Would you mind giving a link to the website which teaches this? Oct 14, 2022 at 19:29
  • Thanks, for your answer. But I don't understand most of your comment as I'm at the beginning of learning. Can you explain in more detail or you can give me a link that explains that in detail? Oct 16, 2022 at 22:56
  • This is the link that tou want geeksforgeeks.org/readwrite-class-objects-fromto-file-c Oct 16, 2022 at 22:58

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Browse other questions tagged or ask your own question.