简体   繁体   中英

char* and unsigned char* casting

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?

After doing a little research, it seemed like an unsigned char array might be a good choice to store the data.

IMO, you could directly store your required structure. Just be sure it is not platform dependent: eg use int32_t instead of int ( C++11 )

struct A{
    ...
};
A a;
file.write(&a, sizeof(a));

For the difference between char and unsigned char, it really depends on you. But you must be coherent:

unsigned char[]...
file.write((unsigned char*)b, 20);

or

char[]...
file.write((char*)b, 20);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM