C ++:使用Boost Serialization来编写/读取文件

时间:2015-02-21 21:00:12

标签: 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();
}

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

P.S。注意之后的一些行,我需要做反向操作:写入myd.dat std :: map foo。

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

1 个答案:

答案 0 :(得分:3)

我有点恼火。您显然正在使用Boost序列化(archive/标题是此库的一部分),但不知何故,您并未对此进行任何说明。因为它很容易证明:

<强> 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"