Reading a Binary File into a bitset or vector<bool>

倾然丶 夕夏残阳落幕 提交于 2019-12-19 21:54:26

问题


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


回答1:


If the file is large, Why should you read once, whole the file into the memory?

You can read a little piece every time. The size is determined with the size in this func:

file.read(buff, size)

When the buff is char's array.

I'm sorry, but You can't simplest read/save vector to file. for more details see here and here.

And use Google, It's very helpful...




回答2:


You didn't give too much context of what you're trying to do in your question. But here's one quick & dirty way to do it:

#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 zero-byte '\0' character into the vector will be false. Any other bytes read in will be treated as true.



来源:https://stackoverflow.com/questions/8380309/reading-a-binary-file-into-a-bitset-or-vectorbool

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!