我试图使用示例从:
https://stackoverflow.com/a/6832677/1816083但是我有:
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'
行:
size_t bytes_read = myfile.read((unsigned char *) buffer, BUFFER_SIZE);
首先,read()
取char*
而不是unsigned char*
。其次,它不返回读取的字符数。
相反,尝试:
myfile.read((char*)buffer, BUFFER_SIZE);
std::streamsize bytes_read = myfile.gcount();
恕我直言,编译器的输出已经足够了。它告诉你,你想让unsigned char*
发挥作用,等待char*
。顺便说一句,甚至还有一个函数名
std::basic_istream<_CharT, _Traits>::read(_CharT*, std::streamsize)
[with _CharT = char ...
如果需要unsigned chars buffer[ ... ]
,则将其强制转换为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();
}