C++:使用 Boost 序列化来写入/读取文件

标签 c++ boost fstream boost-serialization

<分区>

我需要写入/读取包含 std::map 的文件。该文件必须在程序启动时读取(如果存在)。我正在使用 boost 的 fstream,但我得到了这个:

"terminate called after throwing an instance of 'boost::archive::archive_exception'
  what():  input stream error"

好吧,我真的不知道发生了什么..这些是我的台词:

map<int64_t, int64_t> foo;
filesystem::path myFile = GetWorkingDirectory() / "myfile.dat";
[...............] // some code

filesystem::ifstream ifs(myFile);
archive::text_archive ta(ifs);
if (filesystem::exists(myFile)
{
   ta >> foo; // foo is empty until now, it's fed by myFile
   ifs.close();
}

我做错了什么?任何想法? 谢谢。

附言请注意,之后的几行,我需要执行相反的操作:将 std::map foo 写入 myfile.dat。

编辑:如果我使用 std::ifstream,一切正常,将文件保存在我运行应用程序的同一目录中。但是使用 boost 和他的路径,出了点问题。

最佳答案

我有点生气。您显然正在使用 Boost Serialization(archive/ header 是该库的一部分),但不知何故您什么也没说。因为它很容易演示:

Live On Coliru

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/map.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

using namespace boost;

int main() {
    std::map<int64_t, int64_t> foo;
    filesystem::path myFile = filesystem::current_path() / "myfile.dat";

    if (filesystem::exists(myFile))
    {
        filesystem::ifstream ifs(myFile/*.native()*/);
        archive::text_iarchive ta(ifs);

        ta >> foo; // foo is empty until now, it's fed by myFile

        std::cout << "Read " << foo.size() << " entries from " << myFile << "\n";
    } else {
        for (int i=0; i<100; ++i) foo.emplace(rand(), rand());
        filesystem::ofstream ofs(myFile/*.native()*/);
        archive::text_oarchive ta(ofs);

        ta << foo; // foo is empty until now, it's fed by myFile
        std::cout << "Wrote " << foo.size() << " random entries to " << myFile << "\n";
    }

}

打印

Wrote 100 random entries to "/tmp/myfile.dat"

第二次运行时:

Read 100 entries from "/tmp/myfile.dat"

关于C++:使用 Boost 序列化来写入/读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28651273/

相关文章:

C++ moSTLy 冗余默认和参数化构造函数违反 DRY

c++ - Boost::convex_hull 分散的二维点在 STL 容器中

c++ - getline 不适用于 fstream

C++ 保存一个文本文档

c++ - 删除元素后列表的最后一个元素损坏

c++ - c中的自定义PCB闪烁灯

c++ - 多个项目输出类型: compiling as an EXE and a LIB

c++ - 访问派生类中的 protected 成员

ssl - Boost Asio SSL 客户端握手问题

c++ - boost::spirit::lex 不区分大小写的关键字