I was making a program that read binary files. So, I read the individual bytes into unsigned chars (actually reading the data as chars and casting them to unsigned chars for each character). Now I have to write back the unsigned chars to the binary file.
The problem is that now I am forced to write individual bytes after casting them to chars (because write() for binary files expects char* buffer). So, now i have to do the following:
for(int x=0; x<data_size; x++)
{
ch=(char)data[x];
outfile.write(&ch,1);
}
Is there any way to get around this thing so that the amount of I/O operations are reduced in case of reading and writing?
unsigned char ch = 'n'; Both of the Signed and Unsigned char, they are of 8-bits. So for signed char it can store value from -128 to +127, and the unsigned char will store 0 to 255. The basic ASCII values are in range 0 to 127.
The unsinged char type is usually used as a representation of a single byte of binary data. Thus, and array is often used as a binary data buffer, where each element is a singe byte. The unsigned char* construct will be a pointer to the binary data buffer (or its 1st element).
unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.
It generally used to store character values. unsigned is a qualifier which is used to increase the values to be written in the memory blocks. For example - char can store values between -128 to +127, while an unsigned char can store value from 0 to 255 only.
The type of outfile
is ofstream
, right? ofstream
is a typedef
for,
typedef std::basic_ofstream<char, std::char_traits<char> > ofstream;
You need your own typedef
,
typedef std::basic_ofstream<unsigned char, std::char_traits<unsigned char> > uofstream;
And then,
uofstream outfile(...);
outfile.write(data, data_size); //no need to cast
You can do the casting on a pointer...
outfile.write((char *)&data[0], data_size);
the same can be done for reading (i.e. just pass a pointer to the first element of an array of unsigned char casting it to a pointer to char).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With