So far I have code to read an unsigned char from ifstream:
ifstream in;
unsigned char temp;
in.open ("RANDOMFILE", ios::in | ios::binary);
in.read (&temp, 1);
in.close ();
Is this correct? I also tried to write an unsigned char to an ofstream:
ofstream out;
unsigned char temp;
out.open ("RANDOMFILE", ios::out | ios::binary);
out.write (&static_cast(temp), 1);
out.close ();
But I get the following error for writing:
error C2102: '&' requires l-value
And this error for reading:
error C2664: 'std::basic_istream<_elem>::read' : cannot convert parameter 1 from 'unsigned char *' to 'char *'
It would be appreciated if someone could tell me what's wrong with my code or how I can read and write unsigned chars from fstream.
解决方案
The write error is telling you that you are taking the address of the temporary created by static_cast.
Instead of:
// Make a new char with the same value as temp
out.write (&static_cast(temp), 1);
Use the same data already in temp:
// Use temp directly, interpreting it as a char
out.write (reinterpret_cast(&temp), 1);
The read error will also be fixed if you tell the compiler to interpret the data as a char:
in.read (reinterpret_cast(&temp), 1);