如何读/写对象到文件

How to read/write object to a file

本文关键字:文件 对象 何读      更新时间:2023-10-16

我正在尝试将对象的内容保存到文件中,然后读取它们。

我有添加区域,加载现有区域的功能。这些函数使用Area类的对象来保存和加载id、区域名称和区域内的节点数量。

//in the header file
class Area:
{
  public:
  ushort u16ID;
  string sAreaName;
  vector<ushort> nodesList;
};

如何将此写入文件,以便在程序重新启动(即程序关闭然后再次运行)时加载数据

到目前为止,我有以下内容可以从文件中写入和读取:

//In my main .cpp file
//Creating output stream. 
std::ostream& operator<<(std::ostream& out, const Area *objArea) {
  out.write(reinterpret_cast<const char*>(objArea->u16ID),sizeof(objArea->u16ID));
  out.write((objArea->sAreaName.c_str()),sizeof(objArea->sAreaName));
  out.write(reinterpret_cast<const char*>(objArea->nodesList),sizeof(objArea->nodesList));
  return out;
}
//Creating input stream.
istream &operator>>( istream &in, AppAreaRecord *objArea){
  ushort id;
  string name;
  string picName;
  vector<ushort> nodes;
  in.read(reinterpret_cast<char*>(objArea->u16RecordID),sizeof(objArea->u16RecordID));
  in.read(reinterpret_cast<char*>(objArea->sAreaName),sizeof(objArea->sAreaName));
  in.read(reinterpret_cast<char*>(objArea->nodesList),sizeof(objArea->nodesList));
  return in;
}
//Function to load the existing data.
void loadAreas(){
 Area *objArea;
 ifstream in("areas.dat", ios::in | ios::binary);
  in >> objArea;}
}
//Function to write the data to file.
void saveAreas() {
  Area *objArea;
  ofstream out("areas.dat", ios::out | ios::binary | ios::app);
  out << objArea;}

我做错了什么?

下面的内容:

    class Area: {   
   void write(std::ofstream out)    {
           out.write(&u16ID, sizeof(ushort));
           out.write(sAreaName.c_str(), sAreaName.length()+1);
           int ss = nodeList.size();
           out.write(&ss, sizeof(int));
           for (vector<ushort>::iterator it = nodeList.begin(); it != nodeList.end(); it++) {
               out.write(*it, sizeof(ushort));
           }
       } 
 };

如果您有能力使用boost::序列化,我强烈推荐使用它。一旦你设置好了,你可以写文本,xml,二进制,它处理STL容器,类层次结构,指针,智能指针和许多其他的东西。