将包含另一个向量的结构向量写入二进制文件

时间:2016-04-27 20:20:57

标签: c++ vector struct binaryfiles

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

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

我知道这是错误的,因为当我打开文件时,它几乎不足以包含我输入的信息。 所有帮助表示感谢,提前谢谢

1 个答案:

答案 0 :(得分: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;
}

与阅读文件相反。

相关问题