从文件读取文本到无符号字符数组,在尝试使用示例时出错



我试图使用示例从:

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();
}

最新更新