简体   繁体   中英

Long string type not saving properly

I am writing a program to save an email address in a.dat file. I declared the email as in "string Email;" and saved the Email in a.dat file using

ofstream my_file;
my_file.open("Email.dat", ios::in | ios::out | ios::app | ios::binary);
while (!my_file.eof())
{
    p11.Email = Email;
    break;
}

my_file.write((char*)&p11, sizeof(p11));
cout << endl << endl << p11.Email << endl; // just to see if its saving the email properly
my_file.close();

(Here p11 is a class that has the Email variable)

My problem is, whenever I am saving a long string, the p11 Email stores the Email properly, But when I find the Email from the.dat file using file handling again, I notice that for a long Email address it prints a lot of bars as the output. I will also add one screenshot.

在此处输入图像描述

在此处输入图像描述

You cannot do (char*)&p11 . p11.Email internally hides a pointer to the string memory.

You should rather do something like:

ofstream my_file;

// ... write other parts of p11

// write the email length
int l = p11.Email.length();
my_file.write(&l, sizeof(l));

// write the email content
my_file.write(p11.Email.c_str(), l);

You will need to rewrite the read too, to read the length first, resize the string, then read the string.

But serialization is a whole topic in itself. Especially if you want to do it binary as you started with. There's considerations around the padding and packing of structs and whether you want to read it back on the same machine or a different one.

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