C++:对 write/read 个文件使用 Boost 序列化

C++: Use Boost Serialization to write/read files

我需要 write/read 一个包含 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。请注意,之后的几行,我需要执行相反的操作:写入 myfile.dat the std::map foo.

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

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

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"