我已经将 map 序列化了

std::map<std::string, std::string> userandPass;
saveData< std::map<std::string, std::string> >("userandPassBackup.txt", userandPass); // have removed &. why is this needed. i want to pass by reference

使用功能
template <typename SaveClass>
void saveData(const std::string filename, SaveClass& c)
{
// File to be written to
boost::filesystem::remove(boost::filesystem::current_path() /
filename);
boost::filesystem::path myFile = boost::filesystem::current_path() /
filename;
// Declare an output file stream ofs that writes serialises to our
//backup file.
boost::filesystem::ofstream ofs(myFile.native());
// Declare archive ta that will use our output file stream
boost::archive::text_oarchive ta(ofs);
// Write to file
ta << c;
// How many records have been archived?
std::cout << c.size() << " records from have been successfully backed
up to " << myFile << "\n";
}

但是,反序列化(加载)失败,使用:
loadData< std::map<std::string, std::string> >("userandPassBackup.txt", userandPass);

函数在哪里:
template <typename LoadClass>
void loadData(const std::string filename, LoadClass& c)
{
// File to be written to
boost::filesystem::remove(boost::filesystem::current_path() /
filename);
boost::filesystem::path myFile = boost::filesystem::current_path() /
filename;
// Declare an output file stream ofs that writes serialises to our
//backup file.
boost::filesystem::ifstream ifs(myFile.native());
// Declare archive ta that will use our output file stream
boost::archive::text_iarchive ta(ifs);
// Write to file
ta >> c;
// How many records have been archived?
std::cout << c.size() << " records from have been successfully backed
up to " << myFile << "\n";
}

我的项目可以编译,但是当我运行它时,遇到有关输入流的以下错误:

libc++ abi.dylib:以boost::archive::archive_exception类型的未捕获异常终止:输入流错误
中止陷阱:6

我不明白为什么会这样。有人会为我指出正确的方向吗?

谢谢

最佳答案

好像您从loadData复制了saveData主体。您可以通过调用boost::filesystem::remove删除第一步要加载的文件。

10-08 04:58