Debug read / write string to binary

I am trying to write to a binary file, here is my code snippet

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct user
{
    string ID;
    string password;    
};

int main()
{
    fstream afile;
    afile.open("user.dat",ios::out|ios::binary);

    user person;

    person.ID ="001";

    person.password ="abc";

    afile.write (reinterpret_cast <const char *>(&person), sizeof (person));

    person.ID ="002";

    person.password ="def";

    afile.write (reinterpret_cast <const char *>(&person), sizeof (person));

    afile.close();

    afile.open("user.dat",ios::in|ios::binary);


    while (afile.read (reinterpret_cast <char *>(&person), sizeof (person)))
    {
        cout<<person.ID
            <<" "
            <<person.password
            <<endl;

    }

}

I expect my console output to be

001 abc
002 def

Instead i get

002 def 
002 def

Can someone explain to me?

+4
source share
3 answers

std :: string is a class, and its object does not directly store the contents of a string.

An implementation specific to your case, for simplicity, you can understand it as follows:

std :: string has an element that stores a pointer (e.g. ptr) to the actual data.

and

   std::string s = "001";

will not point ptr to the address bar "001"; it will allocate memory and copy the string to that memory. Then when you do

    s = "002";

"002" ; "002" , "001" .

, , .

, , "002" .

, .

+2

, , std::string, . :

afile.open("user.dat",ios::out|ios::binary);

user person;

person.ID ="001";
person.password ="abc";

int len = person.ID.size();
afile.write(reinterpret_cast<char*>(&len), sizeof(len));
afile.write(const_cast<char*>(person.ID.c_str()), len);

len = person.password.size();
afile.write(reinterpret_cast<char*>(&len), sizeof(len));
afile.write(const_cast<char*>(person.password.c_str()), len);

person.ID ="002";
person.password ="def";

afile.close();

afile.open("user.dat",ios::in|ios::binary);

afile.read(reinterpret_cast<char*>(&len), sizeof(len));
person.ID.resize(len);
afile.read(const_cast<char*>(person.ID.c_str()), len);

afile.read(reinterpret_cast<char*>(&len), sizeof(len));
person.password.resize(len);
afile.read(const_cast<char*>(person.password.c_str()), len);

cout << person.ID << " " << person.password << endl;
+2

struct, . , std::string , . , - , , person . , - .

fstream, , :

afile << person.ID << endl;
afile << person.password << endl;

user.dat:

001
abc
002
def

:

afile >> person.ID >> person.password;
while (afile.good())
{
  cout<<person.ID
  <<" "
  <<person.password
  <<endl;
  afile >> person.ID >> person.password;    
}

, std::string.

0

All Articles