Reputation: 1009
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?
Upvotes: 18
Views: 33044
Reputation: 132994
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
Upvotes: 6
Reputation: 114481
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).
Upvotes: 29
Reputation: 9547
When data
is of type unsigned char*
or unsigned char[]
and you just want to write the bits into the file do a pointer cast:
for(int x=0; x<data_size; x++)
{
outfile.write((char*)data + x, 1);
}
As casting removes the issue of one at a time writing:
outfile.write((char*)data, data_size);
And you do it all at once. Note that this outdoes the type checking and therefore is not the best solution.
Upvotes: 2