Howdy, I''ve just started learning how to use binary files (can you believe it? In the years I''ve been programming I''ve only programmed with sequential access text files.)
Anyways, I''ve hit a snag. I''ve got this little program here:
writefile.cpp
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
struct mystruct
{
int x, y;
string myString;
};
int main()
{
ofstream testfile;
mystruct test;
test.x = 123;
test.y = 456;
test.myString = "Hello!";
testfile.open("test", ios::bin | ios::out);
testfile.write (&test, sizeof(test));
testfile.close();
return 0;
}
and this one:
readfile.cpp
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
struct mystruct
{
int x, y;
string myString;
};
int main()
{
ifstream testfile;
mystruct test;
testfile.open("test", ios::bin | ios::in);
testfile.write (&test, sizeof(test));
testfile.close();
cout << "x: " << test.x << endl;
cout << "y: " << test.y << endl;
cout << "string: " << test.myString << endl;
return 0;
}
I run writefile to create a binary file and then readfile to read it back in and cout the data. But I get these results:
I get nothing for the string. I''m betting this has something to do with the dynamic nature of STL strings. But there has to be a workaround for storing strings in a binary file!! What''s the problem?
http://roninmagus.hopto.org
acronymfinder.com - Find any acronym you need!