【C++】【MFC】MFC序列化
用于读写操作文件机制
CFile —— 文件操作类,封装了关于文件读写等操作
CFile::Open (打开文件:file.Open("D:/1.txt", CFile::modeCreate | CFile::modeReadWrite);)
CFile::Write / Read(读写文件:file.Write(str, strlen(str));)
CFile::Close(关闭文件对象)
CFile::SeekToBegin / SeekToEnd / Seek(移动文件指针)
CArchive —— 归档类,完成内存数据的读写
序列化机制步骤:
1、创建文件对象 CFile::Open
2、定义归档对象 CArchive ar
3、数据的序列化 ar << data 反序列化 ar >> data
4、关闭归档对象 ar.Close()
5、关闭文件对象 CFile::Close()
1 #include <afxwin.h> 2 #include <iostream> 3 using namespace std; 4 5 // 序列化 6 void File() { 7 CFile file; 8 file.Open("D:/1.txt", CFile::modeCreate | CFile::modeReadWrite); 9 CArchive ar(&file, CArchive::store, 4096); 10 long age = 18; 11 ar << age; 12 float score = 88.1; 13 ar << score; 14 CString name = "Garry"; 15 ar << name; 16 ar.Close(); 17 file.Close(); 18 } 19 20 // 反序列化 21 void Load() { 22 CFile file; 23 file.Open("D:/1.txt", CFile::modeRead); 24 CArchive ar(&file, CArchive::load, 4096); 25 long age = { 0 }; 26 float score = { 0 }; 27 CString name = { "0" }; 28 ar >> age; 29 ar >> score; 30 ar >> name; 31 32 cout << age << score << name << endl; 33 } 34 35 int main() { 36 File(); 37 Load(); 38 39 return 0; 40 }
CArchive类剖析:
class CArchive{
enum LoadArrayObjType{ typeUndefined = 0, typeCRuntimeClass = 1, typeCObject = 2 };
BOOL m_nMode; //访问方式
int m_nBufSize; //buff大小
CFile* m_pFile; //操作文件对象
BYTE* m_lpBufCur; //当前指向
BYTE* m_lpBufMax; //终止指向
BYTE* m_lpBufStart; //开始指向
}
序列化类对象:
1、类必须派生 CObject
2、类内必须声名宏 DECLARE_SERIAL(class_name)
3、类外必须实现宏 IMPLEMENT_SERIAL(class_name, base_class_name, wSchema)
4、重写父类虚函数 virtual void Serialize(CArchive& ar)
1 #include <afxwin.h> 2 #include <iostream> 3 using namespace std; 4 5 class CMyDocument : public CDocument { 6 DECLARE_SERIAL(CMyDocument) 7 public: 8 int age; 9 float score; 10 CString name; 11 12 CMyDocument(int age = 0, float score = 0.0, CString name = "") : 13 age(age), score(score), name(name) {} 14 virtual void Serialize(CArchive& ar); 15 }; 16 IMPLEMENT_SERIAL(CMyDocument, CDocument, 1) 17 18 void CMyDocument::Serialize(CArchive& ar) { 19 if (ar.IsStoring()) 20 ar << age << score << name; 21 else 22 ar >> age >> score >> name; 23 } 24 25 // 序列化 26 void File() { 27 28 CFile file; 29 file.Open("D:/1.txt", CFile::modeCreate | CFile::modeWrite); 30 CArchive ar(&file, 0); 31 CMyDocument data(18, 88.5, "zhangsan"); 32 ar << &data; 33 ar.Close(); 34 file.Close(); 35 } 36 37 // 反序列化 38 void Load() { 39 CFile file; 40 file.Open("D:/1.txt", CFile::modeRead); 41 CArchive ar(&file, CArchive::load, 4096); 42 CMyDocument* data = NULL; 43 ar >> data; 44 ar.Close(); 45 file.Close(); 46 cout << data->age << data->score << data->name << endl; 47 } 48 49 int main() { 50 //File(); 51 Load(); 52 53 return 0; 54 }