Search code examples
c++boostfstreamboost-serialization

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


I need to write/read a file that contains a std::map. The file must be read at the program start up (if it exists). Im using boost's fstream, but im getting this:

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

Well, i really dont know what is happening.. these are my lines:

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

What im doing wrong? Any idea? Thanks.

P.S. Note that some lines after, i need to do the reverse action: write into myfile.dat the std::map foo.

EDIT: all works if i use std::ifstream, saving the file in the same dir where im running the Application. But using boost and his path, something goes wrong.


Solution

  • I'm a bit miffed. You're clearly using Boost Serialization (the archive/ headers are part of this library) but somehow you're not saying anything about that. Because it's so easy to demonstrate:

    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";
        }
    
    }
    

    Prints

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

    And on second run:

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