Monday, August 25, 2008

CMap serialization

Serialization of CMap
Serialization is a mechanism by which the objects in the memory are stored persistently in the hard diskso that they may be loaded/restored in the future.


Step 1:

Create the object of CmapCMap m_cMap;

Step 2:

Populate the contents of the Cmap

m_cMap[“one”] = 1;

m_cMap[“two”] = 2;
Step 3:

Store it persistently.


If this Cmap object goes out of scope then its values are lost. To persistently store them we write itscontents into a file. Following code snippet shows how to store an object's contents.


CFile cFileG;

if ( cFileG.Open("SampleFile.DB",CFile::modeCreateCFile::modeWrite) )

{CArchive cArchiveObj(&cFileG,CArchive::store);

m_cMap.Serialize(cArchiveObj);}
Step 4:

Load the contents for reinitialization.
Using this file we can initialize any Cmap object of the same type. Following code snippet shows howto load a files contents into an object.


CMap m_cLoadMap;
CFile cFileG;

if ( cFileG.Open("SampleFile.DB",CFile::modeRead) )

{CArchive cArchiveObj(&cFileG,CArchive::load);

m_cLoadMap.Serialize(cArchiveObj);}

No comments: