0

I am writing user-created object to a binary file, everything reads fine when reading from binary file except the string objects, strings have null value inside them, can someone tell a fix?

Here is the class

class User{
private:
    unsigned int user_id;
    std::string user_name, home_address, e_mail;
    char gender, date_of_birth[11];
    unsigned long long int phone;
    bool has_car_booked, is_admin;

    void validate_data();
public:
    void get_data(bool);
    void display();
};

Reading from file

void read_from_file(const std::string &filename){
    std::ifstream file;
    file.open(filename, std::ios::binary | std::ios::in);
    if(!file){
        std::cout<<"Read File does not exist\n";
        return;
    }

    User tempobj;
    file.seekg(0);
    file.read((char*)&tempobj, sizeof(tempobj));
    tempobj.display();
    file.close();   
}

Writing to file

void write_to_file(User &obj, const std::string &filename){

    std::ofstream file;
    file.open(filename, std::ios::binary | std::ios::out);
    file.seekp(0);
    file.write((char*)&obj, sizeof(obj));
    file.close();
}

Please note I am a total beginner to C++ and any help would be appreciated, thanks!

Dev Narula
  • 13
  • 1
  • 3
  • you can't read/write non-trivial types in this way – Alan Birtles Nov 06 '21 at 19:45
  • A `std::string` has a pointer which points at the actuall data (unless it's in short string optimization mode). When you save the string like this, only the pointer is saved. Reading it back and using it will make the program have undefined behavior. – Ted Lyngmo Nov 06 '21 at 19:48

0 Answers0