Read binary file in bits or vector <bool>

How to read binary file in bitset or vector<bool> ? The binary file will vary in length. Is there a better container for this? I am new to C ++, although an experienced programmer.

+4
source share
2 answers

If the file is large, why do you need to read it once, the entire file into memory?

You can read a piece every time. Size is determined using size in this function:

 file.read(buff, size) 

When the buff is a char array.

Sorry, but you cannot read / save the vector to a file in the simplest way. see here and here for more details.

And use Google, it is very useful ...

+2
source

You have not given too much context to what you are trying to do in your question. But here is one quick and dirty way to do this:

 #include <iterator> #include <fstream> #include <vector> #include <assert.h> using namespace std; const char *filename = "foo.bar"; int main() { vector<bool> v; ifstream binary_file(filename, ios::binary); assert(binary_file); copy(istream_iterator<unsigned char>(binary_file), istream_iterator<unsigned char>(), back_insert_iterator< vector<bool> >(v)); } 

Reading the null byte character '\ 0' into the vector will be false. Any other bytes read will be considered true.

-1
source

Source: https://habr.com/ru/post/1384633/


All Articles