赞
踩
本文主要记录一下两点:
1、struct序列化保存
2、vector序列化保存
#include<iostream> #include<Windows.h> #include<vector> #include<fstream> #include<iterator> using std::vector; using std::cout; using std::endl; using std::ifstream; using std::ofstream; const int MAX_DATA = 500; struct stInfo { int nAge; char szName[20]; char chSex; stInfo(int nAge,char* pName,char szSex) { this->nAge = nAge; strcpy_s(this->szName, pName); this->chSex = szSex; } stInfo() { memset(this, 0, sizeof(stInfo)); } stInfo& operator=(const stInfo¶) { this->nAge = para.nAge; strcpy_s(this->szName, para.szName); this->chSex = para.chSex; return *this; } void Print() { cout << "Name:" << szName << "\tYear:" << nAge << "\tSex:" << chSex << endl; } }; int main() { //struct serize, save memory stInfo info(19, "helen", 'M'); BYTE *pSrc(new BYTE[MAX_DATA]); ZeroMemory(pSrc, MAX_DATA); *(stInfo*)pSrc = info; //Write ofstream fout("1.txt", std::ios::out | std::ios::binary); if (fout.is_open()) { fout.write((char*)pSrc, sizeof(stInfo)); fout.close(); } delete[]pSrc; pSrc = nullptr; //Read char szData[MAX_DATA] = { 0 }; ifstream fin("1.txt", std::ios::binary); if (fin.is_open()) { fin.read(szData, MAX_DATA); fin.close(); } BYTE *pData = new BYTE[MAX_DATA]; ZeroMemory((void*)pData, MAX_DATA); pData = (BYTE*)szData; stInfo infoRst; infoRst = *(stInfo*)pData; infoRst.Print(); delete[]pData; pData = nullptr; //vector Serize vector<int>vecData; for (int nIndex = 0; nIndex < 5; ++nIndex) vecData.push_back(nIndex); //写入文件 ofstream outFile("test.txt", std::ios::out | std::ios::binary); if (outFile.is_open()) { copy(vecData.begin(), vecData.end(), std::ostream_iterator<int>(outFile," ")); outFile.close(); } //从文件读取 vector<int>vecRst; ifstream inFile("test.txt", std::ios::binary); if (inFile.is_open()) { copy(std::istream_iterator<int>(inFile), std::istream_iterator<int>(), back_inserter(vecRst)); inFile.close(); } for (auto&itData : vecRst) cout << itData << ','; cout << endl; //从文件读取直接输出 copy(vecData.begin(), vecData.end(), std::ostream_iterator<int>(cout, " ")); system("pause"); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。