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 = 78; 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 CSerializableObj::Serialize( CArchive& archive )
{
// call base class function first
// base class is CObject in this case
CObject::Serialize( archive );
// now do the stuff for our specific class
if( archive.IsStoring() )
{
// TODO: add storing code here
}
else
{
// TODO: add storing 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 CEmployee::Serialize( CArchive& archive )
{
// call base class function first
// base class is CObject in this case
CObject::Serialize( archive );
// now do the stuff for our specific class
if( archive.IsStoring() )
archive << m_strName << m_wAge;
else
archive >> m_strName >> 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 |
|
备注
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:
archive << m_strName << m_wAge;