Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Archive class for WTL

0.00/5 (No votes)
14 Jan 2004 3  
A port of MFC CArchive class to simplify serialization in WTL and non-MFC projects

Introduction

WTL (Windows Template Library) is another library from Microsoft that we can use to create Windows applications. WTL was created by a few Microsoft developers as an extension to ATL and was designed to make a GUI creation a much simpler process. WTL is based on C++ templates and allows developers to create small in size and fast applications. But, unfortunately, since WTL is not supported by Microsoft and it is being developed by just a few programmers it is missing some nice features long existing in MFC.


One of such features 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!

CXArchive declaration

class CXArchive
{
public:
  // Flag values

  enum Mode { store = 0, load = 1, bNoFlushOnDelete = 2 };

  CXArchive(CXFile* pFile, UINT nMode, int nBufSize = 4096, 
    void* lpBuf = NULL);
  ~CXArchive();

  // These functions access the mode to determine the state 

  // of the CXArchive object

  BOOL IsLoading() const;
  BOOL IsStoring() const;

  CXFile* GetFile() const;

  // Operations

  UINT Read(void* lpBuf, UINT nMax);
  void Write(const void* lpBuf, UINT nMax);
  void Flush();
  void Close();
  void Abort();   // close and shutdown without exceptions


  // Reading and writing strings

  void WriteString(LPCTSTR lpsz);
  LPTSTR ReadString(LPTSTR lpsz, UINT nMax) throw(CXArchiveException);
  BOOL ReadString(CString& rString);

  // Insertion operations

  CXArchive& operator<<(BYTE by);
  CXArchive& operator<<(WORD w);
  CXArchive& operator<<(LONG l);
  CXArchive& operator<<(DWORD dw);
  CXArchive& operator<<(float f);
  CXArchive& operator<<(double d);
  CXArchive& operator<<(LONGLONG dwdw);
  CXArchive& operator<<(ULONGLONG dwdw);
  CXArchive& operator<<(int i);
  CXArchive& operator<<(short w);
  CXArchive& operator<<(char ch);
#ifdef _NATIVE_WCHAR_T_DEFINED
  CXArchive& operator<<(wchar_t ch);
#endif
  CXArchive& operator<<(unsigned u);
  CXArchive& operator<<(bool b);

  // Extraction operations

  CXArchive& operator>>(BYTE& by);
  CXArchive& operator>>(WORD& w);
  CXArchive& operator>>(DWORD& dw);
  CXArchive& operator>>(LONG& l);
  CXArchive& operator>>(float& f);
  CXArchive& operator>>(double& d);
  CXArchive& operator>>(LONGLONG& dwdw);
  CXArchive& operator>>(ULONGLONG& dwdw);
  CXArchive& operator>>(int& i);
  CXArchive& operator>>(short& w);
  CXArchive& operator>>(char& ch);
#ifdef _NATIVE_WCHAR_T_DEFINED
  CXArchive& operator>>(wchar_t& ch);
#endif
  CXArchive& operator>>(unsigned& u);
  CXArchive& operator>>(bool& b);

protected:
  // Archive objects can not be copied or assigned

  CXArchive(const CXArchive& arSrc) {}
  void operator=(const CXArchive& arSrc) {}

  void FillBuffer(UINT nBytesNeeded) throw(CXArchiveException);

  CXFile * m_pFile;
  string m_strFileName;

  BOOL m_bDirectBuffer;   
  BOOL m_bBlocking;    
  BOOL m_nMode;      
              
  BOOL m_bUserBuf;
  int m_nBufSize;
  BYTE * m_lpBufCur;
  BYTE * m_lpBufMax;
  BYTE * m_lpBufStart;
};

CXArchive description

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. To understand how CXArchive is working we'll take a look at the implementation of the insertion and extraction operators for LONG.

Insertion operator:

CXArchive& CXArchive::operator<<(LONGl) 
{
  if (m_lpBufCur + sizeof(LONG) >  m_lpBufMax) 
    Flush();
    
  *(UNALIGNED LONG*)m_lpBufCur = l; 
  m_lpBufCur += sizeof(LONG);

  return *this; 
}

The insertion operator checks to see if it needs to flush the internal CXArchive buffer, places the LONG in the buffer and increments the buffer pointer. It returns a CXArchive reference to allow the insertion operators to be cascaded.

Extraction operator:

CXArchive& CXArchive::operator>>(LONG&l) 
{
  if (m_lpBufCur + sizeof(LONG) >  m_lpBufMax)
    FillBuffer((UINT)(sizeof(LONG) - (m_lpBufMax - m_lpBufCur)));
    
  l = *(UNALIGNED LONG*)m_lpBufCur; 
  m_lpBufCur += sizeof(LONG); 
  
  return *this; 
}

The extraction operator checks to see if it needs to get more data from the file into the internal buffer, then it places a LONG worth of data from the buffer into the LONG reference argument. As a last step it increments the buffer pointer to prepare for the next extraction.

Using the code

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 file1;
  file1.Open(strFile,                  
    GENERIC_WRITE | GENERIC_READ,       
    FILE_SHARE_READ | FILE_SHARE_WRITE,    
    NULL,                  
    CREATE_ALWAYS,              
    FILE_ATTRIBUTE_NORMAL,          
    NULL);                  

  CXArchive ar1(&file1, CXArchive::store);
  
  CDriver driver1;
  driver1.Serialize(ar1);

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

To de-serialize it:

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

  CXArchive ar2(&file2, CXArchive::load);
    
  CDriver driver2;
  driver2.Serialize(ar2);

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

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.

Conclusion

It's very easy to serialize your objects using CXArchive class. For basic types just use the insertion /extraction operators. For more complex types call their Serialize method, just do not forget to pass the CXArchive argument to them.

History

  • 01/12/2004 - Initial release.

Disclaimer

THIS SOFTWARE AND THE ACCOMPANYING FILES ARE DISTRIBUTED "AS IS" AND WITHOUT ANY WARRANTIES WHETHER EXPRESSED OR IMPLIED. NO RESPONSIBILITIES FOR POSSIBLE DAMAGES CAN BE TAKEN. THE USER MUST ASSUME THE ENTIRE RISK OF USING THIS SOFTWARE.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here