StickysoftDESIGNS
Skip Navigation Links : Articles : WTL : Archive class for WTL

Archive class for WTL

One of such missing features in WTL is a serialization support that is provided by a CArchive class in MFC. To remedy this I decided to port CArchive class to WTL to simplify the serialization in WTL and non-MFC applications.
Thus CXArchive class was born!

Internally CXArchive is using CXFile class to write and read data to and from a file (CXFile is another class developed by me and it is basically a wrapper class for Windows file APIs.). Class CXArchive is tied to a CXFile class pointer and implements buffering for better performance.
One note: if you used new to allocate the CFile object on the heap, then you must delete it after closing the file. Close sets file pointer to NULL.

How to use it

You use the CXArchive class in exactly the same way as you would use the CArchive class.
In your class implement a Serialize() function like this:

void CDriver::Serialize(CXArchive& ar)
{
    if (ar.IsStoring())
    {
        ar << m_byte;
        ar << m_word;
    }
    else
    {
        ar >> m_byte;
        ar >> m_word;
    }
}
    

Then somewhere in your code add the following lines.

To serialize your class:

string strFile = "demo.txt";

try
{
    CXFile file;
    file.Open(strFile,                  
        GENERIC_WRITE | GENERIC_READ,       
        FILE_SHARE_READ | FILE_SHARE_WRITE,    
        NULL,                  
        CREATE_ALWAYS,              
        FILE_ATTRIBUTE_NORMAL,          
        NULL);                  

    CXArchive ar(&file, CXArchive::store);
  
    CMyClass myclass;
    myclass.Serialize(ar);

    ar.Close();
}
catch (CXException& Ex)
{
    MessageBox(NULL, Ex.GetErrorDesc().c_str(), "Archive Demo", MB_OK);
}
    

To de-serialize it:

{
    CXFile file;
    file.Open(strFile,                  
        GENERIC_WRITE | GENERIC_READ,      
        FILE_SHARE_READ | FILE_SHARE_WRITE,    
        NULL,                  
        OPEN_EXISTING,              
        FILE_ATTRIBUTE_NORMAL,          
        NULL);                  

    CXArchive ar(&file, CXArchive::load);
    
    CMyClass myclass;
    myclass.Serialize(ar);

    ar.Close();
}
catch (CXException& Ex)
{
    MessageBox(NULL, Ex.GetErrorDesc().c_str(), "Archive Demo", MB_OK);
}
Download the source code