【问题标题】:Serialize multiple text files using boost C++使用 boost C++ 序列化多个文本文件
【发布时间】:2021-07-16 04:00:36
【问题描述】:

是否可以使用 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();

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

【问题讨论】:

  • 你可以有一个向量的向量
  • 如何定义“序列化多个文本文件”?根据定义,文件不是已经序列化了吗?
  • 我正在尝试将文本文件读取到向量中,对其进行序列化,然后将其恢复。但是,我需要同时执行 3 次,这就是问题所在。
  • 如何“同时”想要这个?如果你线程化它,线程可能会开始争夺对磁盘的访问权并最终变慢。
  • 请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?

标签: c++ vector serialization boost text-files


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 2020-01-15
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    相关资源
    最近更新 更多