Search code examples
c++vectorunsigned-charistream-iterator

What is the template argument when reading a binary file to "unsigned char" vector


What's wrong with this code?

std::vector<unsigned char> newVector;
std::ifstream inFile(fullPath.c_str(), std::ios::in|std::ios::binary);
std::istreambuf_iterator iterator(inFile);

It gives me this:

missing template arguments before 'iterator'

And if I change it to this:

std::istreambuf_iterator<unsigned char> iterator(inFile);

It complains this:

invalid conversion from 'void*' to 
    'std::istreambuf_iterator<unsigned char>::streambuf_type

Solution

  • ifstream is a basic_ifstream<char>, not a basic_ifstream<unsigned char>. Therefore, you need to declare iterator as

    std::istreambuf_iterator<char> iterator(inFile);
    

    and it will work.