tmighty
tmighty

Reputation: 11399

C++ determining size of data before writing it to a file

I am serializing some data to a file like this:

vector<ByteFeature>::iterator it = nByteFeatures.Content().begin();
for (;it != nByteFeatures.Content().end(); ++it)
{
    for ( int i = 0; i < 52; i++)
    {
        fwrite( &it->Features[i], sizeof(unsigned char), 1, outfile);
    }
}   

But I would like to know in advance how much bytes that will be in the file. I would like to write this number in front of the actual data. Because in some situations I will have to skip loading this data, and I need to know how many bytes I have to skip.

There is more data written to the disk, and it would be crucial to me that I can write the number of bytes directly before the actual data. I do not want to store this number in a separate file or so.

 .Content.size() would only tell me how many "items" are in there, but not the actual size of the data.

Thank you.

Upvotes: 0

Views: 420

Answers (2)

rwols
rwols

Reputation: 3078

You are writing 52 unsigned chars to a file for every ByteFeature. So the total number of bytes you are writing is 52 * nByteFeatures.Contents().size(), assuming that one char equals one byte.

Upvotes: 2

Andy Thomas
Andy Thomas

Reputation: 86409

I've had to do this before myself.

The approach I took was to write a 4-byte placeholder, then the data, then fseek() back to the placeholder to write the length.

  • Write a 4-byte placeholder to the file.
  • ftell() to get the current file position.
  • Write the data to the file.
  • ftell() to get the new position.
  • Compute the length: the difference between the two ftell() values.
  • Then fseek() back to the placeholder and write the length.

Upvotes: 4

Related Questions