GILGAMESH
GILGAMESH

Reputation: 1856

How can I read and write unsigned chars to files with fstream in 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.

Upvotes: 5

Views: 13012

Answers (2)

Drew Dormann
Drew Dormann

Reputation: 63704

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

Upvotes: 8

thiton
thiton

Reputation: 36049

The read function always takes bytes as arguments, represented as char values for convenience. You can cast the pointer to these bytes around as much as you want, so

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

will read a single byte just fine. Remember that memory is memory is memory, and the types of C++ are just an interpretation of memory. When you are reading raw bytes into raw memory (as with read), you should read first and then cast to the appropriate type.

Upvotes: 2

Related Questions