This article will show you how you can serialize data to disk and retrieve it
again in non doc/view architecture projects. Just follow the steps outlined.
Steps to follow
- Create a normal project as you usually do.
- Add the class which you would use to serialize the data. It might contain
just normal variables or collection classes or any kind of data that you want
- Be sure to derive that class from
CObject. Only then you can serialize
- Be sure to use the
DECLARE_SERIAL macro inside.
class CInfo : public CObject
virtual void Serialize(CArchive& ar);
Add the serialization function in this class's .cpp file. Be sure to use the
IMPLEMENT_SERIAL macro as shown.
void CInfo::Serialize(CArchive& ar)
ar >> m_strName;
ar >> m_nIndex;
ar << m_strName;
ar << m_nIndex;
As this example is concerned with just 2 variables, assume that 2
edit controls have been created to accommodate the Index and the Name. Add 2
variables to those edit controls using the Class Wizard. Now the File to which
the data has to be written or read from has to be defined. I do that simply by
#define DATA_FILE _T("Accounts.dat")
Now, we write the code for storing the data to the disk. Here,
m_bCanSave is declared in the header file as
and in the constructor it has been initialized as
m_bCanSave = FALSE;
UINT nFlags = CFile::typeBinary | CFile::modeWrite;
if (_access(DATA_FILE, 0))
nFlags |= CFile::modeCreate;
m_bCanSave = TRUE;
int nTemp = _access(DATA_FILE, 6);
m_bCanSave = TRUE;
if (file.Open(DATA_FILE, nFlags, &fe))
CArchive ar(&file, CArchive::store);
Info.m_nIndex = m_nIndex;
Info.m_strName = m_strName;
Now , we write the code for reading the data from the disk.
if (_access(DATA_FILE, 6)==0)
if (file.Open(DATA_FILE,CFile::typeBinary |
CArchive ar(&file, CArchive::load);
m_nIndex = Info.m_nIndex;
m_strName = Info.m_strName;
That's it. A Simple tutorial for serialization is complete. You have a
program that can serialize data to the disk and retrieve it later. You didn't
know that serialization was so easy. Did you? All Luck and have a nice time.