svick
svick

Reputation: 245046

Safely writing bytes to stream

I need to write bytes to a file. The natural representation for a byte is std::uint8_t. The problem is that istream.read() and ostream.write() work with chars. I could convert between the two types, e.g.:

char c;
input.read(&c, 1);
uint8_t b = (uint8_t)c;
uint8_t b = …;
char c = (char)b;
output.write(&c, 1);

That could be a problem because char is often a signed type and AFAIK there is no guarantee what the bit pattern that is written will be the same as what the int8_t originally contained.

I need to make sure this works across compilers and OSes, so that if I write something on one computer, it will be read the same on any other one.

Is there any standards-compliant way to do this?

Upvotes: 3

Views: 528

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477650

The conversion from unsigned char to char and back is perfectly fine, and it's exactly what you should be doing. All three char types are layout compatible.

You only have to be careful with any non-char integral types and convert them to uint8_t first before converting to char, etc., and similarly in the other direction.

Upvotes: 1

Related Questions