【问题标题】:Reading text from file to unsigned char array, errors while trying to use example [closed]从文件读取文本到无符号字符数组,尝试使用示例时出错[关闭]
【发布时间】:2013-02-22 08:54:53
【问题描述】:

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

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

【问题讨论】:

  • 这可能是您链接到的答案没有获得一票的部分原因。 ;)
  • @NPE 现在有一个。嗯,就是 -1。
  • 您是否只想将整个文件放入一个线性数组中并读取一次大容量?还是您一次处理一个缓冲区大小?
  • 我建议标记不恰当的答案,这会导致这个问题(stackoverflow.com/a/6832677/1816083),删除,它会混淆人们

标签: c++ arrays file unsigned-char


【解决方案1】:

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

请尝试:

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

【讨论】:

  • 来自unsigned char*' to char*' 的无效转换可能包括丢失?我是 cpp 的菜鸟
  • @cerber 从缓冲区的定义中删除单词unsigned
  • @kassak 他需要它作为unsigned char 数组(见问题的标题)。他应该在.read() 调用的第一个参数中添加一个(char *)
  • @WhozCraig 是的,错过了这个,只看问题的正文
  • #include #include #include #include using namespace std; int main() { const unsigned int BUFFER_SIZE = 1024;无符号字符缓冲区[BUFFER_SIZE]; //... ifstream myfile("myfile.bin", ios::binary); if (myfile) { size_t bytes_read = myfile.read(( char *) 缓冲区,BUFFER_SIZE); } 返回 0; } 来自void*' to size_t'的无效转化
【解决方案2】:

恕我直言,编译器的输出已经足够了。它告诉你,你正试图让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();
}

【讨论】:

  • stackoverflow.com/a/6832677/1816083 ,所以这个例子不好,如何正确地做到这一点?
  • @cerber 你一直相信人们什么?)
  • “所以这个例子很糟糕” - 是的。 “如何正确地做到这一点?” - 将buffer 声明为char 的数组或将其转换为char* 而不是unsigned char*
  • 但我需要 uchar 数组
  • 然后将其转换为char*。顺便说一句,您选择了否定投票的答案,而还有另一个答案=)
猜你喜欢
  • 2011-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多