Reading a Binary File into a bitset or vector

后端 未结 2 480
面向向阳花
面向向阳花 2021-01-19 14:38

How do I read a binary file into a bitset or vector? The binary file will vary in length. Is there a better container for this? I am ne

2条回答
  •  佛祖请我去吃肉
    2021-01-19 15:28

    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 
    #include 
    #include 
    #include 
    using namespace std;
    
    const char *filename = "foo.bar";
    int main()
    {
      vector v;
      ifstream binary_file(filename, ios::binary);
    
      assert(binary_file);
      copy(istream_iterator(binary_file),
           istream_iterator(),
           back_insert_iterator< vector >(v));
    }
    

    Reading the zero-byte '\0' character into the vector will be false. Any other bytes read in will be treated as true.

提交回复
热议问题