Carchive is a data stream file editor defined in MFC. It can be used to conveniently and efficiently save data as binary files, saving us a lot of trouble.
When using carchive, in addition to built-in data types, serialization is required for custom classes or structures. Specifically, if it is a class derived from cobject, You can reload the serialize function. For general classes or structures, you can add a member function to save and load it internally.
In particular, if all the data members in the structure are of a fixed length, they can be saved in bytes. However, if a string pointer exists, data will be lost when it is saved in bytes.
For some data classes, the version number should be declared. If the class is derived from cobject, you can add a version control flag to the implement_serial macro. If it is a custom class, you can write the current version number when saving the class, and read the code based on the version number.
Version Control:
IMPLEMENT_SERIAL(CMyObject, CObject, VERSIONABLE_SCHEMA|1)
Read data based on different versions:
void CMyObject::Serialize(CArchive& ar) { if (ar.IsLoading()) { int nVersion = ar.GetObjectSchema(); switch(nVersion) { case 0: // read in previous version of // this object break; case 1: // read in current version of // this object break; default: // report unknown version of // this object break; } } else { // Normal storing code goes here }}
Write and read byte data:
GUID id;CoCreateGuid(&id);arStore.Write(&id, sizeof(GUID));
GUID id;arLoad.Read(&id, sizeof(GUID));
Write and read the cobject derived class:
class CAge : public CObject{DECLARE_SERIAL( CAge )private:int m_years;public:CAge() { m_years = 0;}CAge( int age ) { m_years = age;}CAge( const CAge& a ) { m_years = a.m_years;} // Copy constructorvoid Serialize( CArchive& ar);void AssertValid() const;const CAge& operator=( const CAge& a ){m_years = a.m_years;return *this;}BOOL operator==(CAge a){return (m_years == a.m_years);}//void* operator new(size_t nSize);//void* operator new(size_t nSize, LPCSTR lpszFileName, int nLine);//void operator delete(void* p);//void operator delete(void* p, LPCSTR lpszFileName, int nLine);#ifdef _DEBUGvoid Dump( CDumpContext& dc ) const{CObject::Dump( dc );dc << m_years; }#endif};
CAge myAge(24);arStore.WriteObject(&myAge);
CObject* pLoadObj = arLoad.ReadObject(RUNTIME_CLASS(CAge));if(pLoadObj->IsKindOf(RUNTIME_CLASS(CAge))){CAge* pAge = dynamic_cast<CAge*>(pLoadObj);if (pAge){afxDump.SetDepth( 1 );pAge->Dump(afxDump);delete pAge;pAge = NULL;}}