简体   繁体   中英

Read and write structure containing std::string to .dat file using std::write and std::read C++

I have a structure

struct details
{
   std::string username;
   std::string password;
   bool isActive;
};

struct details v_Details;

i wish to write these data into a file and then read it at some other point in the code as means of storing details. I have tried using std::write which seems to do its job

std::ofstream out_file;
out_file.open ("db.dat" , ios::out | ios::binary)
out_file.write((char*)&v_details , sizeof (struct details))

but when i try to read the data it reads only username and password and then it crashes.

My read part of the code is as below

std::ifstream in_file;
in_file.open (fileName.c_str() , std::ifstream::in);

std::string readFileLine = "\0";

if (in_file.is_open())
{
    do
    {
        in_file.read ((char*)&details , sizeof(details));
        cout << "\nDEBUG message-> " << __FILE__ <<" : " << __func__ << " : " << __LINE__ << " : Read - "<< details.username << " " << details.password << " " << isActive ;
    }while (!in_file.eof());

in_file.close();
}

Anybody who can help and provide me a fix on this.

You cannot directly write the object and expect it to store everything properly when you have members that don't have a fixed size. If it were char array you could use this way.

Given this situation, I would manually write the details, like length of username first, then write characters in username so that while reading I can read the length of username and read that number of characters from file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM