如何读取/写入文件的对象

时间:2011-11-18 20:44:20

标签: c++ file

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

我有添加区域,加载现有区域的功能。这些函数使用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;}

我做错了什么?

2 个答案:

答案 0 :(得分:1)

有些事情:

    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));
           }
       } 
 };

答案 1 :(得分:0)

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