Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read and write unsigned chars to files with fstream in c++?

Tags:

c++

visual-c++

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<char>(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,_Traits>::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.

like image 490
GILGAMESH Avatar asked Dec 29 '11 14:12

GILGAMESH


1 Answers

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<char>(temp), 1);

Use the same data already in temp:

// Use temp directly, interpreting it as a char
out.write (reinterpret_cast<char*>(&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<char*>(&temp), 1);
like image 190
Drew Dormann Avatar answered Sep 28 '22 04:09

Drew Dormann