Okay you have strings here. That's your problem. Strings are a complex type. As such, you should never write them directly as binary data. Here's the reason why:
string might look something like this:
1 2 3 4 5 6
|
class string
{
private:
char* buffer;
int length;
};
|
The actual string data is not stored in the string itself. Instead, string just has a pointer that points to the data. Now when you write a string to a binary file,
only the pointer gets written. It does not write the actual string data.
Here's a simple way you can test to see what I mean:
1 2 3 4 5 6 7 8 9 10
|
int main()
{
string foo = "This is a very long string.";
foo += " It will definitely be longer than a few bytes.";
ofstream myfile;
myfile.open("file.bin", std::fstream::binary | std::fstream::app | std::fstream::out );
myfile.write( reinterpret_cast<char*>(&foo), sizeof(foo) );
}
|
If you do that, you'll notice the file it makes is only a few bytes. The size doesn't change depending on how large the actual string data is.
What's more, when you read this from the file... instead of reading string data... instead you are just reading a pointer. (but that pointer doesn't point to what it used to! So it ends up pointing to nothing/garbage, which makes your program explode).
So instead, you want to read/write the string data, not the string object. There are a few ways to do this. Here's one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
void WriteString(ofstream& file,const string& str)
{
// get the length of the string data
unsigned len = str.size();
// write the size:
file.write( reinterpret_cast<const char*>( &len ), sizeof(len) );
// write the actual string data:
file.write( str.c_str(), len );
}
string ReadString(ifstream& file)
{
// this probably isn't the optimal way to do it, but whatever
string str;
// get the length
unsigned len;
file.read( reinterpret_cast<char*>( &len ), sizeof(len) );
// we can't read to string directly, so instead, create a temporary buffer
if(len > 0)
{
char* buf = new char[len];
file.read( buf, len );
str.append( buf, len );
delete[] buf;
}
return str;
}
|