首页 > 解决方案 > 使用 boost C++ 序列化多个文本文件

问题描述

是否可以使用 boost 序列化多个文本文件?到目前为止,我有一个系统可以正常读取文本文件,如下所示:

std::ifstream readFile(afile);

while (afile) // While reading file
{
    getline(afile, input); // Reads file, stores it in input. 
    vecTest.push_back(input); // Gets words from input and stores them in vector. 
}
readFile.close();

这将读取文件并将内容存储到向量中。为了序列化向量的内容,我使用下一段代码:

std::ofstream readFile("serialise.txt");
boost::archive::text_oarchive archiveFile(readFile);

archiveFile << vecTest;
readFile.close();

加载后如何设置它以添加其他文本文件?

标签: c++vectorserializationboosttext-files

解决方案


档案是结构化的流。他们已经组织了序列化到同一个存档的不同对象。

所以在这里你可以很容易地:

using File = std::vector<std::string>;
File f1{100, "file 1 line"},
     f2{200, "file 2 line"},
     f3{300, "file 3 line"};

{
    std::ofstream ofs("ondisk.txt");
    boost::archive::text_oarchive oa(ofs);
    oa << f1 << f2 << f3;
}

然后,我们可以检查:

f1.clear(); // oh no...
f2.clear(); // looks like we
f3.clear(); // forgot the data

{
    std::ifstream ifs("ondisk.txt");
    boost::archive::text_iarchive ia(ifs);
    ia >> f1 >> f2 >> f3;
}

std::cout << "Remembered " << f1.size() << "/" << f2.size() << "/" << f3.size() << " lines\n";

哪些打印(Live On Coliru):

Remembered 100/200/300 lines

推荐阅读