Home > front end >  How to write vector<bool> to binary file?
How to write vector<bool> to binary file?

Time:05-09

I need to write a boolean vector to a binary file. I searched stackoverflow for similar questions and didn't find anything that worked. I tried to write it myself, here's what I came up with:

vector<bool> bits = { 1, 0, 1, 1 };

ofstream file("file.bin", ios::out | ios::binary);

uint32_t size = (bits.size() / 8)   ((bits.size() % 8 == 0) ?  0 : 1);

file.write(reinterpret_cast<const char*>(&bits[0]), size);

I was hoping it would write 1011**** (where * is a random 1/0). But I got an error:

error C2102: '&' requires l-value

Theoretically, I could do some kind of loop and add 8 bools to char one by one, then write the char to a file, and then repeat many times. But I have a rather large vector, it will be very slow and inefficient. Is there any other way to write the entire vector at once. Bitset is not suitable since I need to add bits to the vector.

CodePudding user response:

vector<bool> may or may not be packed and you can't access the internal data directly, at least not portable.

So you have to iterate over the bits one by one and combined them into bytes (yes, bytes, c has bytes now, don't use char, use uint8_t for older c ).

As you say writing out each byte is slow. But why would you write out each byte? You know how big the vector is so create a suitable buffer, fill it and write it out in one go. At a minimum write out chunks of bytes at once.

CodePudding user response:

Since vector<bool> doesn't have the data() function, getting the address of its internal storage requires some ugly hacks (although it works for listdc I strongly discourage it)

file.write(
  reinterpret_cast<const char*>(
    *reinterpret_cast<std::uint64_t* const*>(&bits)), 
  size);
  • Related