.h文件如下:
#pragma once class CMyData : public CObject { public: CPoint pt; int m_iData; char buff[10]; 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; ar.Write(buff[i],10); } else { ar >> pt >> m_iData; ar.Read(buff[i],10); } }
在调用ar.WriteString后,需再用此方法写入:ar.WriteString(_T("\n"));
调用方法如下:
//写入内容 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); 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();
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。