Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost serialization end of file

I serialize multiple objects into a binary archive with Boost. When reading back those objects from a binary_iarchive, is there a way to know how many objects are in the archive or simply a way to detect the end of the archive ?

The only way I found is to use a try-catch to detect the stream exception. Thanks in advance.

like image 259
Shnippoo Avatar asked Jul 12 '11 14:07

Shnippoo


People also ask

What is serialization in C++?

Serialization is the process of writing or reading an object to or from a persistent storage medium such as a disk file. Serialization is ideal for situations where it is desired to maintain the state of structured data (such as C++ classes or structures) during or after execution of a program.

How do you serialize an object in C++?

Serializing whole objects To unserialize an object, it should have a constructor that takes byte stream. It can be an istream but in the simplest case it can be just a reference uint8_t pointer. The constructor reads the bytes it wants from the stream and sets up the fields in the object.

What is serialization used for?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.


1 Answers

I can think of a number of approaches:

  1. Serialize STL containers to/from your archive (see documentation). The archive will automatically keep track of how many objects there are in the containers.

  2. Serialize a count variable before serializing your objects. When reading back your objects, you'll know beforehand how many objects you expect to read back.

  3. You could have the last object have a special value that acts as a kind of sentinel that indicates the end of the list of objects. Perhaps you could add an isLast member function to the object.

  4. This is not very pretty, but you could have a separate "index file" alongside your archive that stores the number of objects in the archive.

  5. Use the tellp position of the underlying stream object to detect if you're at the end of file:

Example (just a sketch, not tested):

std::streampos archiveOffset = stream.tellg(); 
std::streampos streamEnd = stream.seekg(0, std::ios_base::end).tellg();
stream.seekg(archiveOffset);

while (stream.tellp() < streamEnd)
{
    // Deserialize objects
}

This might not work with XML archives.

like image 189
Emile Cormier Avatar answered Sep 22 '22 04:09

Emile Cormier