echoscot
Programmer
- Apr 11, 2007
- 2
I have to serialize some string data to a binary file:
example:
string name = "My Name";
ofstream fout("file.dat", ios:ut|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?
example:
string name = "My Name";
ofstream fout("file.dat", ios:ut|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?