Export (0) Print
Expand All
0 out of 1 rated this helpful - Rate this topic

Using the CArchive << and >> Operators 

CArchive provides << and >> operators for writing and reading simple data types as well as CObjects to and from a file.

To store an object in a file via an archive

  • The following example shows how to store an object in a file via an archive:

    CArchive ar(&theFile, CArchive::store);
    WORD wEmployeeID;
    ...
    ar << wEmployeeID;
    

To load an object from a value previously stored in a file

  • The following example shows how to load an object from a value previously stored in a file:

    CArchive ar(&theFile, CArchive::load);
    WORD wEmployeeID;
    ...
    ar >> wEmployeeID;
    

Usually, you store and load data to and from a file via an archive in the Serialize functions of CObject-derived classes, which you must have declared with the DECLARE_SERIALIZE macro. A reference to a CArchive object is passed to your Serialize function. You call the IsLoading function of the CArchive object to determine whether the Serialize function has been called to load data from the file or store data to the file.

The Serialize function of a serializable CObject-derived class typically has the following form:

void CPerson::Serialize(CArchive& ar)
{
    CObject::Serialize(ar);
    if (ar.IsStoring())
    {
        // TODO:  add storing code here
    }
    else
    {
    // TODO:  add loading code here
    }
}

The above code template is exactly the same as the one AppWizard creates for the Serialize function of the document (a class derived from CDocument). This code template helps you write code that is easier to review, because the storing code and the loading code should always be parallel, as in the following example:

void CPerson:Serialize(CArchive& ar)
{
    if (ar.IsStoring())
    {
        ar << m_strName;
        ar << m_wAge;
    }
    else
    {
        ar >> m_strName;
        ar >> m_wAge;
    }
}

The library defines << and >> operators for CArchive as the first operand and the following data types and class types as the second operand:

CObject*

SIZE and CSize

float

WORD

CString

POINT and CPoint

DWORD

BYTE

RECT and CRect

double

LONG

CTime and CTimeSpan

int

COleCurrency

COleVariant

COleDateTime

COleDateTimeSpan

 

NoteNote

Storing and loading CObjects via an archive requires extra consideration. For more information, see Storing and Loading CObjects via an Archive.

The CArchive << and >> operators always return a reference to the CArchive object, which is the first operand. This enables you to chain the operators, as illustrated below:

BYTE bSomeByte;
WORD wSomeWord;
DWORD wSomeDoubleWord;
...
ar << bSomeByte << wSomeWord << wSomeDoubleWord;

See Also

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.