到目前为止,我有代码从ifstream读取unsigned char:
ifstream in;
unsigned char temp;
in.open ("RANDOMFILE", ios::in | ios::binary);
in.read (&temp, 1);
in.close ();
这是对的吗?我还尝试将一个unsigned char写入ofstream:
ofstream out;
unsigned char temp;
out.open ("RANDOMFILE", ios::out | ios::binary);
out.write (&static_cast<char>(temp), 1);
out.close ();
但是我写错了以下错误:
error C2102: '&' requires l-value
这个错误的阅读:
error C2664: 'std::basic_istream<_Elem,_Traits>::read' : cannot convert parameter 1 from 'unsigned char *' to 'char *'
如果有人能告诉我我的代码有什么问题,或者我如何从fstream读取和写入未签名的字符,我们将不胜感激。
答案 0 :(得分:8)
写入错误告诉您正在使用static_cast
创建的临时地址。
而不是:
// Make a new char with the same value as temp
out.write (&static_cast<char>(temp), 1);
在temp中使用相同的数据:
// Use temp directly, interpreting it as a char
out.write (reinterpret_cast<char*>(&temp), 1);
如果您告诉编译器将数据解释为char,那么读取错误也将得到修复:
in.read (reinterpret_cast<char*>(&temp), 1);
答案 1 :(得分:2)
read
函数始终将字节作为参数,为方便起见,表示为char
值。您可以根据需要将指针转换为这些字节,所以
in.read (reinterpret_cast<char*>(&temp), 1);
将读取单个字节就好了。请记住,内存是内存是内存,而C ++的类型只是对内存的解释。当您将原始字节读入原始内存时(与read
一样),您应先读取然后转换为适当的类型。