如何读/写对象到文件
How to read/write object to a 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;}
我做错了什么?
下面的内容:
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容器,类层次结构,指针,智能指针和许多其他的东西。
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何在h文件中包含.o对象文件
- 如何使用单独文件中的派生类访问友元函数对象
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 使用逗号解析文件对象?
- 使用 CIN COUT 显示垃圾值的文件对象?
- 如何确保我的"ifstream"文件对象指向的文件内容已更新?
- 如何从 GDI+ 图元文件对象获取原始图元文件字节
- pyQt5 将文件对象传递给 QWebEngineView
- 从文件对象的当前位置删除字符
- 使用相同的文件对象按顺序写入和读取文件
- 将 ETW 文件对象与 DiskIO 事件相关联
- 如何在构建时将 JSON 文件/对象包含在C++中
- 如何使用运算符<<通过 << 将文件对象馈送到我的类?
- 确定两个文件路径引用同一文件对象的最佳方法是什么
- 文件映射对象和文件对象可以互换使用吗
- 如何判断给定点是否在STereoLithography(.stl)文件对象c++内
- 如何使用Windows Portable Devices C++API获取MTP设备公开的文件夹中的所有文件(对象)的列
- 如何使用结构传递文件对象
- 文件对象->文件名不返回文件的完整路径