I learn Visual C++ with Visual Studio 2010. I tried to use Serialize function of MFC CObject. I can't load my object with Serialize function My code:
#include <afxwin.h>
#include <iostream>
using std::cout;
using std::endl;
// CMyObject
class CMyObject : public CObject
{
public:
int x, y;
CMyObject(int _x=0, int _y=0) : CObject(), x(_x), y(_y) {}
void Serialize(CArchive &ar);
void Print() const;
DECLARE_SERIAL(CMyObject)
};
IMPLEMENT_SERIAL(CMyObject, CObject, 1)
void CMyObject::Serialize(CArchive &ar)
{
CObject::Serialize(ar);
if (ar.IsStoring())
ar << x;
else
ar >> x;
}
void CMyObject::Print() const
{
cout << "CMyObject (" << x << "," << y << ")" << endl;
}
int main()
{
CMyObject cm(1,3);
CFile fileS, fileL;
fileS.Open(L"C:\\CMyObject.dat", CFile::modeWrite | CFile::modeCreate);
CArchive arStore(&fileS, CArchive::store);
cm.Print();
cm.Serialize(arStore);
arStore.Close();
cm.x = 2;
cm.Print();
fileL.Open(L"C:\\CMyObject.dat", CFile::modeRead);
CArchive arLoad(&fileL, CArchive::load);
cm.Serialize(arLoad);
cm.Print();
arLoad.Close();
}
Program died on the string:
cm.Serialize(arLoad);
Could you tell me what's wrong with this code?
You should be checking the calls to Open()
for failure. You forgot to close the file after you finished writing to it. Add fileS.Close();
after you close the archive object.
if(!fileS.Open(L"C:\\source\\CMyObject.dat", CFile::modeWrite | CFile::modeCreate))
{
std::cout << "Unable to open output file" << std::endl;
return 1;
}
CArchive arStore(&fileS, CArchive::store);
cm.Print();
cm.Serialize(arStore);
arStore.Close();
fileS.Close(); // <--- close the file
if(!fileL.Open(L"C:\\source\\CMyObject.dat", CFile::modeRead))
{
std::cout << "Unable to open input file" << std::endl;
return 1;
}
CArchive arLoad(&fileL, CArchive::load);
cm.Serialize(arLoad);
cm.Print();
arLoad.Close();
fileL.Close(); // <--- close the file