关于结构体的文件存储及读取的有关问题
关于结构体的文件存储及读取的问题
关于以下结构体中数据的二进制文件的存储与读取:
typedef struct point
{
int x;
CPoint begin;
CPoint end;
}point;
typedef std::vector<point> ar_point;
ar_point m_point;
我写了一个存储的函数(存储产生的文件是二进制的),有没有人能够给出一个读取的函数?或者是相关的源代码的下载链接?
(废话不给分)
void CXView::Save()
{
ofstream ofs("SaveFile.dat",ios::binary);
INT i = 0;
for(std::vector<point_x_y>::iterator it = m_point.begin();it != m_point.end();it++)
{
ofs.write((char*)&m_point[i],sizeof(m_point));
i++;
}
ofs.close();
}
------解决方案--------------------
关于以下结构体中数据的二进制文件的存储与读取:
typedef struct point
{
int x;
CPoint begin;
CPoint end;
}point;
typedef std::vector<point> ar_point;
ar_point m_point;
我写了一个存储的函数(存储产生的文件是二进制的),有没有人能够给出一个读取的函数?或者是相关的源代码的下载链接?
(废话不给分)
void CXView::Save()
{
ofstream ofs("SaveFile.dat",ios::binary);
INT i = 0;
for(std::vector<point_x_y>::iterator it = m_point.begin();it != m_point.end();it++)
{
ofs.write((char*)&m_point[i],sizeof(m_point));
i++;
}
ofs.close();
}
------解决方案--------------------
- C/C++ code
#include <iostream> #include <fstream> #include <vector> using namespace std; typedef struct point { int x; CPoint begin; CPoint end; }point; class CXView { public: typedef std::vector<point> ar_point; ar_point m_point; void Init(); void Draw(); void Save(); void Load(); }; void CXView::Init() { point pt; pt.x = 100; pt.begin = CPoint( 1, 2 ); pt.end = CPoint( 3, 4 ); m_point.push_back( pt ); pt.x = 200; pt.begin = CPoint( 11, 22 ); pt.end = CPoint( 33, 44 ); m_point.push_back( pt ); } void CXView::Draw() { for( vector< point >::iterator it = m_point.begin(); it != m_point.end(); ++it ) { cout << it->x << " " << it->begin.x << " " << it->begin.y << " " << it->end.x << " " << it->end.y << endl; } } void CXView::Save() { ofstream ofs("SaveFile.dat",ios::binary); int len = m_point.size(); ofs.write( (char*)&len, sizeof(len) ); INT i = 0; for(std::vector<point>::iterator it = m_point.begin();it != m_point.end();it++) { ofs.write((char*)&m_point[i],sizeof(point)); i++; } ofs.close(); } void CXView::Load() { m_point.clear(); ifstream ifs("SaveFile.dat",ios::binary); int len; ifs.read( (char*)&len, sizeof( len ) ); for( int i1 = 0; i1 < len; ++i1 ) { point pt; ifs.read( (char*)&pt, sizeof(point) ); m_point.push_back( pt ); } ifs.close(); } int main() { CXView view; view.Init(); view.Save(); view.Draw(); cout << "--------------------华丽丽的分隔线--------------------" << endl; view.Load(); view.Draw(); return 0; }