0
votes

I'm trying to read a binary file stream into a std::vector buffer.

std::ifstream file(srcPath, std::ifstream::binary);
file.unsetf(std::ios::skipws);
const std::vector<unsigned char> buffer(bufferSize);
file.read(buffer.data(), bufferSize);

But I get the following error

Cannot initialize a parameter of type 'std::__1::basic_istream >::char_type *' (aka 'char *') with an rvalue of type 'const std::__1::vector >::value_type *' (aka 'const unsigned char *')

I'm having trouble interpreting this error and figuring out what I'm doing wrong in my call to read.

2

2 Answers

3
votes
const std::vector<unsigned char> buffer(bufferSize);

You declared a const object here. By definition, a const object cannot be modified. Your plans to modify this object, by reading something into it, are already doomed to a big, abysmal, failure at this point. But there's also a second problem.

file.read(buffer.data(), bufferSize);

If you actually read your compiler's error message, slowly, it tells you exactly what the problem is.

First of all, read()s first parameter is a char *, a pointer to a character.

But you are passing a const unsigned char *. That's because data(), given that buffer is const, obviously returns a const unsigned char *.

And that's why you get a compilation error. If you now reread the compilation error, skipping about half of its words, it makes perfect sense now:

Cannot initialize a parameter of type ... 'char *' with an rvalue of type ... 'const unsigned char *'

To fix it, your buffer should not be a const object. Preferrably, it should be a std::vector<char>, so you end up really passing a char * to read().

But, if you insist, you can keep it a vector of unsigned chars and use reinterpret_cast to cast the result of data() from unsigned char * to char *.

3
votes

You made your vector const.

So, you cannot change its contents.

You want to change its contents (that's its purpose).

So, don't make it const.