#pragma once class CMyData : public CObject { public: CPoint pt; int m_iData; public: DECLARE_SERIAL(CMyData) CMyData(){} CMyData(int nData, CPoint pt1) { m_iData = nData; pt = pt1; } virtual void Serialize(CArchive& ar); };
.cpp文件内容如下:
#include "stdafx.h" #include "mytest.h" IMPLEMENT_SERIAL(CMyData, CObject, 1) void CMyData::Serialize(CArchive& ar) { CObject::Serialize(ar); if (ar.IsStoring()) { ar << pt << m_iData; } else { ar >> pt >> m_iData; } }
调用方法如下:
//写入内容 CMyData d(12,CPoint(1,8)); CFile file(_T("1.txt"), CFile::modeCreate | CFile::modeWrite); //串行化,存储 CArchive ar(&file, CArchive::store); ar.WriteCount(1); ar.WriteObject(&d); ar.Close(); file.Close(); //读取内容 CFile mFile; if (mFile.Open(_T("1.txt"), CFile::modeRead) == 0) return 0; char buf[512]; CArchive ar(&mFile, CArchive::load, 512, buf); unsigned long length = ar.ReadCount();//按写入顺序,读取存储的数据单元个数 CMyData * pData; for (int i = 0; i < length; i++) { //读取一个类信息,同时指针移动到下一个类信息开始 pData = (CMyData *)ar.ReadObject(RUNTIME_CLASS(CMyData)); cout << pData->m_iData << endl; cout <<"x="<< pData->pt.x << " y=" << pData->pt.y << endl; } ar.Close(); mFile.Close();
原文地址:http://blog.51cto.com/9233403/2051112