4

I need to read and write binary data in my program. After doing a little research, it seemed like an unsigned char array might be a good choice to store the data.

I open the file in binary mode using the ios::binary flag, but when I go to read or write, the ifstream::read() and ofstream::write() functions are expecting a char* and const char*.

So, I have to cast my unsigned char* to a char* every time I want to read or write.

I don't think this will make any difference but I'm starting to wonder if I should just use a regular char array to store the data instead. I have seen people use both char and unsigned char arrays for this purpose and I don't fully understand the difference.

Let's say I have 2 arrays:

char a[20];
unsigned char b[20];

Now I open a file in binary mode and read:

file.read(a, 20);
file.read((char*)b, 20);

Now I want to write this data to a new file so I open in binary mode again:

newfile.write(a, 20);
newfile.write((char*)b, 20);

What's the difference? Am I better off just using a char array instead of an unsigned char array for binary data?

James
  • 101
  • 2
  • 1
    It's normal for file-/binary-reading interfaces to use `char*` as the go to type for "pointer to a byte". In your case, reading bytes into `unsigned char[]` is perfectly safe, and the cast to `char*` is also perfectly safe. You should use `reinterpret_cast` to make it clear that you're just temporarily viewing the array as `char*` instead of `unsigned char[20]`. – GManNickG Dec 20 '15 at 18:23

1 Answers1

0

A signed char is typically considered to hold textual data, while an unsigned char represents a byte, not necessarily of ASCII value. The convention then is to use unsigned char for binary data, as whether char is signed or not is implementation dependent.

The data type you choose for your data should influence what functions you use, rather than the other way around.

adisib
  • 197
  • 7