Read binary file into vector of uint32_t

2019-08-16 05:50发布

问题:

There's a binary file words.bin containing multiple 4 byte integers. I want to read them from the file into a std::vector of corresponding size, which is uint32_t. Here's what I've tried first:

#include <fstream>
#include <iterator>
#include <vector>
#include <cstdint>

int main(int argc, char* argv[])
{
    std::ifstream f("words.bin", std::ios::in | std::ios::binary);
    std::vector<uint32_t> wordvec(std::istreambuf_iterator<uint32_t>{f}, {});

    return 0;
}

However, I get this error message:

u32vec.cpp: In function 'int main(int, char**)':
u32vec.cpp:9:71: error: no matching function for call to 'std::istreambuf_iterator<unsigned int>::istreambuf_iterator(<brace-enclosed initializer list>)'
     std::vector<uint32_t> wordvec(std::istreambuf_iterator<uint32_t>{f}, {});

If I change both uint32_t to char, it does work, but this is not what I want.

My second try was writing the curly bracket notation explicitly, but then accessing the methods of std::vector gives a syntax error. This is the code:

#include <fstream>
#include <iterator>
#include <vector>
#include <cstdint>

int main(int argc, char* argv[])
{
    std::ifstream f("words.bin", std::ios::in | std::ios::binary);
    std::vector<uint32_t> wordvec(std::istreambuf_iterator<uint32_t>(f), std::istreambuf_iterator<uint32_t>());

    wordvec.at(0);

    return 0;
}

And this is the compiler output:

u32vec.cpp: In function 'int main(int, char**)':
u32vec.cpp:11:13: error: request for member 'at' in 'wordvec', which is of non-class type 'std::vector<unsigned int>(std::istreambuf_iterator<unsigned int>, std::istreambuf_iterator<unsigned int> (*)())'
     wordvec.at(0);
             ^~

This is the output of g++ --version:

g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.