C++ C++;:使用Boost序列化来写入/读取文件
我需要写/读一个包含std::map的文件。必须在程序启动时读取该文件(如果存在)。我在使用boost的流媒体,但我得到的是:C++ C++;:使用Boost序列化来写入/读取文件,c++,boost,fstream,boost-serialization,C++,Boost,Fstream,Boost Serialization,我需要写/读一个包含std::map的文件。必须在程序启动时读取该文件(如果存在)。我在使用boost的流媒体,但我得到的是: "terminate called after throwing an instance of 'boost::archive::archive_exception' what(): input stream error" 嗯,我真的不知道发生了什么事。。以下是我的台词: map<int64_t, int64_t> foo; filesystem::
"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();
}
map-foo;
filesystem::path myFile=GetWorkingDirectory()/“myFile.dat”;
[……]//一些代码
文件系统::ifstream ifs(myFile);
存档:文本存档ta(ifs);
if(filesystem::exists)(myFile)
{
ta>>foo;//foo到目前为止是空的,它由myFile提供
ifs.close();
}
我做错了什么?知道吗?
谢谢
注意,在后面的一些行中,我需要执行相反的操作:将std::map foo写入myfile.dat
编辑:如果我使用std::ifstream,将文件保存在运行应用程序的同一目录中,则所有操作都有效。但是使用boost和他的路径时,出现了一些问题。我有点生气。显然,您使用的是boost序列化(存档/标题是此库的一部分)但不知怎的,你什么也没说。因为这很容易证明:
#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";
}
}
第二次运行时:
Read 100 entries from "/tmp/myfile.dat"
你的实际输入是什么?我没有输入就尝试了(删除文件)还有一个file.dat,我以前用std::ofstream.的同样方法创建了它。两人都给了我上面的错误。一个文件怎么可能包含一个
std::map
?afaikw在链接中它在一个文件中谈论std::map
?我看不到它。首先感谢你的及时回复。很抱歉,我的问题写得不好,但我很抱歉你说得对。我的代码和你的例子一模一样。那我为什么会出错呢?我很困惑。编辑:我解决了更改路径的问题。不知道为什么,但现在它工作正常。不过,谢谢,
Read 100 entries from "/tmp/myfile.dat"