从文件读取文本到unsigned char数组,尝试使用示例时出错

时间:2013-03-07 08:34:27

标签: c++ arrays file unsigned-char

我正在尝试使用以下示例:

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

2 个答案:

答案 0 :(得分:3)

首先,read()需要char*而不是unsigned char*。其次,它不会返回读取的字符数。

相反,请尝试:

myfile.read((char*)buffer, BUFFER_SIZE);
std::streamsize bytes_read = myfile.gcount();

答案 1 :(得分:1)

恕我直言,编译器的输出非常有用。它告诉您,您正试图让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();
}