Считать двоичный файл в вектор uint32_t - PullRequest
0 голосов
/ 09 марта 2019

Есть двоичный файл words.bin, содержащий несколько 4-байтовых целых чисел.Я хочу прочитать их из файла в std::vector соответствующего размера, который равен uint32_t.Вот что я попробовал в первую очередь:

#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;
}

Тем не менее, я получаю это сообщение об ошибке:

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}, {});

Если я изменю оба uint32_t на char, это работает,но это не то, что я хочу.

Моя вторая попытка была записать явно фигурные скобки, но затем доступ к методам std::vector дает синтаксическую ошибку.Это код:

#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;
}

А это вывод компилятора:

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);
             ^~

Это вывод 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.
...