Read binary file into vector of uint32_t

痴心易碎 提交于 2019-12-24 11:28:21

问题


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.

来源:https://stackoverflow.com/questions/55073202/read-binary-file-into-vector-of-uint32-t

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