Reading text from file to unsigned char array, errors while trying to use example [closed]

☆樱花仙子☆ 提交于 2019-12-12 03:46:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!