0

I'm trying to use boost library to serialize std::map so that is possible to store it in a file. However I'm having so weird behaviours (i guess). So here is my code:

#include <map>
#include <fstream>
#include <iostream>
#include <bitset>

#include <boost/serialization/map.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

std::map<int,int> map = {{65,2}, {69,1}, {75,1} ,{77,1}, {82,1}, {84,2}, {89,2}};

void saveMapToFile(std::ofstream& f);

int main()
{
    std::ofstream f("test.txt", std::ios::binary);

    saveMapToFile(f);

    std::cout << "position: " << f.tellp() << std::endl;
}

void saveMapToFile(std::ofstream& f)
{
    std::cout << "position : " << f.tellp() << std::endl;

    boost::archive::text_oarchive oarch(f);

    std::cout << "position : " << f.tellp() << std::endl;

    oarch << map;

    std::cout << "position : " << f.tellp() << std::endl;
}

And here is the above code's output:

position : 0
position : 28
position : 75
position: 76

So can someone explain to me what is happening here? Why position after insterting map (in function) in different outside of it? I don't do any additional opperations, yet that pointer goes one byte further... Am I missing something? Thanks for your help in advance.

peter Schiza
  • 387
  • 7
  • 23

1 Answers1

0

I don't see why you would be making assumptions about the implementation of the archive format.

Archives write headers, and can write "trailers" (think XML archives).

The destructor of oarch wrote another byte, finishing the stream. It could be a sentinel, a checksum, a newline etc.

sehe
  • 374,641
  • 47
  • 450
  • 633
  • Yeah i understand that, but i don't understand why it is inconsistent. I mean i want to save other data after that map in a file and I have problem with that. Where should i execute that storing? If i save the other data in that function ```saveMapToFile()``` it starts from 75th byte and if i do it outside it goes on 76th byte. Then when reading - after i read the map, pointer position always goes to 75th byte, yet that other data might start from 76th byte so in that moment I am not sure do i have to just start reading data or move on the next byte and then read.Maybe i don't understand smth. – peter Schiza Nov 01 '16 at 09:20
  • You have to pass the archive, not the stream to your save function. – sehe Nov 01 '16 at 10:08
  • 1
    See also the bottom-most links in [this answer](https://stackoverflow.com/a/28395831/85371): [Outputting more things than a Polymorphic Text Archive](http://stackoverflow.com/questions/27422557/outputting-more-things-than-a-polymorphic-text-archive/27424381#27424381) and [Streams are not archives](http://www.boost.org/doc/libs/1_51_0/libs/serialization/doc/) – sehe Nov 01 '16 at 10:11