问题
I'm trying to use example from:
https://stackoverflow.com/a/6832677/1816083 but i have:
invalid conversion from `unsigned char*' to `char*'
initializing argument 1 of `std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::read(_CharT*, std::streamsize) [with _CharT = char, _Traits = std::char_traits<char>]'
invalid conversion from `void*' to `size_t'
in line:
size_t bytes_read = myfile.read((unsigned char *) buffer, BUFFER_SIZE);
回答1:
Firstly, read()
takes a char*
rather than unsigned char*
. Secondly, it does not return the number of characters read.
Instead, try:
myfile.read((char*)buffer, BUFFER_SIZE);
std::streamsize bytes_read = myfile.gcount();
回答2:
IMHO the compiler's output is quite enought. It tells you, that you're trying to give unsigned char*
to function, that waits char*
. BTW, there is even a function name
std::basic_istream<_CharT, _Traits>::read(_CharT*, std::streamsize)
[with _CharT = char ...
If you need unsigned chars buffer[ ... ]
then cast it to char*
unsigned char buffer[ BUFFER_SIZE ];
ifstream myfile("myfile.bin", ios::binary);
if (myfile)
{
myfile.read((char*) buffer, BUFFER_SIZE);
// ^^^^^^^
size_t bytes_read = myfile.gcount();
}
来源:https://stackoverflow.com/questions/15266448/reading-text-from-file-to-unsigned-char-array-errors-while-trying-to-use-exampl