C++/writing a struct with bit fields into a file.
Expert: Zlatko - 1/9/2012
Questionhalo mr. zlatko.
this question is simple but it's part of a much larger project.
the issue is writing a structure that contains bit fields into a file. the bit fields are of two, i.e. everything is to encoded using just two bits instead of eight bits.
struct test{unsigned y:2}fun;
above is sample code (so simple) as to what i need to be written into the file. within the main function:
int main ()
{ unsigned w;
ofstream afile ("result",ios::binary)
for (w=0;w<=255;w++)
{ unsigned f;
f=3&w;
fun.y=f;
afile<<fun.y;}
afile.close();
the above code does not work as i wish it would. please help me out, remember, i want to know how to write a structure containing bit fields into a file, or how to write characters encoded using two bits into a file, e.g. number 1 can be encoded using two bits:01 instead of eight:00000001.writing it into the file encoded in two bits would save me more space.
THANKS IN ADVANCE AND GOD BLESS YOU.
AnswerHello Trey.
When writing to files, the smallest data type which can be use is the byte. You cannot write individual bits to a file. Before writing, you will need to pack all your bit fields into bytes, and write them out as bytes.
You might also be surprised that the size of your test structure will be a multiple of 4 bytes even if the bit fields can fit in fewer bytes. If you can pack your structure so that it has many bit fields, and if you don't mind a little wasted space, you can write the entire structure to disk with ofstream::write
If you want to minimize the space in memory and in the file, you can use my BitFields class which I describe in this answer.
http://en.allexperts.com/q/C-1040/2011/12/dynamic-bit-fields-1.htm
You would need to add a method to the class to handle writing to a file.
Have a look at that answer and it may give you what you need.
Best regards
Zlatko