在MFC中将类串行化存储
.h文件如下:
创新互联公司主营平川网站建设的网络公司,主营网站建设方案,app软件开发公司,平川h5小程序定制开发搭建,平川网站营销推广欢迎平川等地区企业咨询
#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();
网站栏目:在MFC中将类串行化存储
链接URL:http://scyanting.com/article/josceh.html