如何读取和写入无符号字符到C++中的fstream文件?

问题描述:

到目前为止,我有代码来读取从ifstream的unsigned char类型:如何读取和写入无符号字符到C++中的fstream文件?

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读取和写入无符号字符,请加以理解。

写入错误告诉您,您正在使用由static_cast创建的临时地址。

相反的:

// Make a new char with the same value as temp 
out.write (&static_cast<char>(temp), 1); 

使用已经在温度相同的数据:

// Use temp directly, interpreting it as a char 
out.write (reinterpret_cast<char*>(&temp), 1); 

读取错误也会,如果你告诉编译器来解释数据作为一个char固定:

in.read (reinterpret_cast<char*>(&temp), 1); 

The read function alw ays以字节为参数,为方便起见,表示为char值。你可以把指针指向这些字节,只要你想要,所以

in.read (reinterpret_cast<char*>(&temp), 1); 

会读取一个字节就好了。请记住,内存是内存,而C++的类型只是内存的一种解释。当您将原始字节读入原始内存时(与read一样),您应该先阅读并转换为适当的类型。