问题
I have developed a C++ application for reading and writing data on a random access file. (I use Visual C++ 2010)
Here is my program:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class A
{
public :
int a;
string b;
A(int num , string text)
{
a = num;
b = text;
}
};
int main()
{
A myA(1,"Hello");
A myA2(2,"test");
cout << "Num: " << myA.a<<endl<<"Text: "<<myA.b<<endl;
wofstream output; //I used wfstream , becuase I need to wite a unicode file
output.open("12542.dat" , ios::binary );
if(! output.fail())
{
output.write( (wchar_t *) &myA , sizeof(myA));
cout << "writing done\n";
output.close();
}
else
{
cout << "writing failed\n";
}
wifstream input;
input.open("12542.dat" , ios::binary );
if(! input.fail())
{
input.read( (wchar_t *) &myA2 , sizeof(myA2));
cout << "Num2: " << myA2.a<<endl<<"Text2: "<<myA2.b<<endl;
cout << "reading done\n";
}
else
{
cout << "reading failed\n";
}
cin.get();
}
And output is:
Num: 1
Text: Hello
writing done
Num2: 1
Text2: test
reading done
But i expect Text2: Hello
.
What is the problem??
By the way , How can I do output.write
inside of my class ( in a function) ?
Thanks
回答1:
A is not POD, you can not brutally cast non-POD object to char*
then write to stream.
You need to serialize A
, for example:
class A
{
public :
int a;
wstring b;
A(int num , wstring text)
{
a = num;
b = text;
}
};
std::wofstream& operator<<(std::wofstream& os, const A& a)
{
os << a.a << " " << a.b;
return os;
}
int main()
{
A myA(1, L"Hello");
A myA2(2, L"test");
std::wcout << L"Num: " << myA.a<<endl<<L"Text: "<<myA.b<<endl;
wofstream output; //I used wfstream , becuase I need to wite a unicode file
output.open(L"c:\\temp\\12542.dat" , ios::binary );
if(! output.fail())
{
output << myA;
wcout << L"writing done\n";
output.close();
}
else
{
wcout << "writing failed\n";
}
cin.get();
}
This sample serializes object myA to file, you can think about how to read it out.
来源:https://stackoverflow.com/questions/14393774/reading-random-access-files