Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Serializing Strings

Status
Not open for further replies.

echoscot

Programmer
Joined
Apr 11, 2007
Messages
2
I have to serialize some string data to a binary file:

example:

string name = "My Name";

ofstream fout("file.dat", ios::out|ios::binary)

int size = name.size();

fout.write(reinterpret_cast<char*>(&size), sizeof(int));

fout.write(reinterpret_cast<char*>(&name), sizeof(size));

fout.read(reinterpret_cast<char*>(&size), sizeof(int));

fout.read(reinterpret_cast<char*>(&name), sizeof(size));

cout<<" name is: "<<name;

the above crashes just after printing "name is ", then won't print the string it just crashes. Also have tried variations, like write/read((char*)&name, sizeof(string)),

wondering if there is a specific trick to this?
 
You should write the string's data, not the sring itself, since it is not a POD:
Code:
fout.write(reinterpret_cast<char*>(&name.data()), size);
There's some other issues with that code (you shouldn't read from an ofstream). When you do read you should be reading into a vector or a temporary char array, and then transferring into the string, since you cannot directly modify the contents of a string.
Code:
vector<char> temp(size);
fin.read(reinterpret_cast<char*>(&temp[0]), size);
name.assign(temp.begin(), temp.end());
My syntax might be a bit off but that's the idea.
 
Thank you that is very helpful about the vector/array to read into. I actually did set up a separate ifstream object, unlike the pseudocode I posted.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top