Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing unsigned chars to a binary file using write()

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?

like image 633
c0da Avatar asked Aug 09 '11 12:08

c0da


People also ask

How do you write an unsigned char?

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.

What is unsigned char pointer?

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

What is unsigned char array?

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.

Why do we use unsigned char in C?

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.


2 Answers

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
like image 32
Armen Tsirunyan Avatar answered Sep 28 '22 01:09

Armen Tsirunyan


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

like image 79
6502 Avatar answered Sep 28 '22 01:09

6502