【问题标题】:writing a vector of structs that contain another vector to a binary file将包含另一个向量的结构向量写入二进制文件
【发布时间】:2016-04-27 20:20:57
【问题描述】:

我一直在尝试将其写入文件,但无济于事我找到了一种方法,我还需要能够从中读取。这是结构

struct details
{
    float balance=0;
    vector<string> history;
    string pin;
};
struct customer
{
    int vectorID;
    string name; 
    char type;  
    details detail;
};
vector<customer> accounts;

我现在拥有的是:

ofstream fileBack;
fileBack.open("file.txt", ios::in|ios::binary|ios::trunc);

fileBack.write(reinterpret_cast<char*>(&accounts), accounts.size()*sizeof(accounts));
fileBack.close();

而且我知道这是错误的,因为当我打开文件时,它还不足以包含我放入其中的信息。 感谢所有帮助,提前感谢您

【问题讨论】:

  • 你找到了错误的方式。
  • 是的,我想,我只是在黑暗中拍摄,希望有什么东西能粘住

标签: c++ vector struct binaryfiles


【解决方案1】:

一个非常简单的方法是使用Boost Serialization。您需要在每个类中定义一个成员函数来处理序列化,例如:

void details::serialize(Archive & ar, const unsigned int version) {
    ar & balance;
    ar & history;
    ar & pin;
}


void customer::serialize(Archive & ar, const unsigned int version) {
    ar & vectorID;
    ar & name; 
    ar & type;  
    ar & detail;
}

然后,当您想添加到文件时,您可以这样做:

std::ofstream ofs("filename", std::ios::binary); // binary file open
....
// save data to archive
{
    boost::archive::text_oarchive oa(ofs);
    // write class instance to archive
    oa << yourCustomerClass;
}

与读取文件相反。

【讨论】:

  • 谢谢!我将尝试实现这一点并得到我的结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
相关资源
最近更新 更多