首页 > 解决方案 > 如何将 id 写入文件然后将其读回?

问题描述

所以我需要一个静态数字来计算对象的数量,然后将其分配给 id。然后我需要让这个 id 唯一,这样它就不能再使用了,即使我关闭应用程序并再次打开它也是如此。我怎么做?

piggyBank.cpp

int PiggyBank::nrOfObjects = 0; // outside constructor

PiggyBank::getNrOfObjects(){

return nrOfObjects;

}

PiggyBank::PiggyBank(void){
  {this->owner="";this->balance=0;this->broken=false;}
  id = ++nrOfObjects;
}

PiggyBank::PiggyBank(std::string name){
  { this->owner=name;this->balance=0;this->broken=false; }
  id = ++nrOfObjects;
}

PiggyBank::PiggyBank(std::string name, int startBalance){
    {this->owner=name;this->balance=startBalance;this->broken=false;}
    id = ++nrOfObjects;
   }

piggyBank.h

private:
    std::string owner; // PiggyBank owner
    int balance; // Current balance in PiggyBank
    bool broken; // true if PiggyBank is broken, else false
    int id;
    static int nrOfObjects;
public:
    PiggyBank(void);

    PiggyBank(std::string name);

    PiggyBank(std::string name, int startBalance);

    static int getNrOfObjects();

标签: c++

解决方案


您可以使用fstream写入文件和ifstream读取文件。例如:

#include <fstream>
using namespace std;

为了写入文件:

fstream out_file {filename,ios::out | ios::binary);}; //create file
out_file.write((char*)&pointerToObject, sizeof(obj)); //write data to file
out_file.close();                                     //close the file

为了从文件中读取:

ifstream ifile;                                       
ifile.open(filename, ios::in | ios::binary);          //open file
ifile.seekg (0, ifile.end);
ifile length = ifile.tellg();                         //get file length
ifile.seekg (0, ifile.beg);
char * buffer = new char [length];                    //create buffer
ifile.read(buffer,length);                            //read from file to buffer
ifile.close();                                        //close file
delete[] buffer;                                      

推荐阅读