简体   繁体   中英

How to read/write object to a file

I'm trying to save the contents of an object into a file, and then read them.

I have functions that Add an Area, Load an existing Area. These functions use objects of the Area class to save and load the id, area name and the number of nodes in the area.

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

How do i write this to a file, so as to load the data when the program restarts (ie the program is closed and then run again).

I have the following until now to write and read into/from a file:

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

What am I doing wrong?

Something along the lines of:

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

If you can afford to use boost::serialization , I strongly recommend it. Once you've got it set up, you can write to text, xml, binary, it handles STL containers, class hierarchies, pointers, smart pointers and many many other things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM