c++ - 如何将 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();
解决方案
您可以使用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;
推荐阅读
- c++ - 具有可分离程序的 OpenGL 统一块绑定
- jupyter-notebook - 如何保存 Jupyter Notebook 的输出?
- c# - dotnet core OData 3.1 - 不返回正确的记录
- javascript - 遍历嵌套数组对象
- algorithm - 如何以某种方式对随机数进行评分,数字越低,它给出的分数就越多?
- r - 在 R 中创建具有可变数量的 *named* 参数的函数
- next.js - NextJS - 在 getServerSideProps 中获取 url
- javascript - Nuxt.js + vuetify 图像未加载
- c++ - 无法让 dup2 为我自己的命令重定向输出,但适用于 execvp
- html - 如何在 Visual Studio 中填充 HTML 工具箱?