C++/saving a structure to a file.
Expert: vijayan - 1/9/2012
Questionhalo mr. vijayan.
my question is relatively simple (i am new to programming).
how do you write a structure to a file?the structure contains bit fields of 2:
struct dante {unsigned jey:2}vergil;
this is the structure. how do i write it to a file ensuring that only two bits will be used to store the characters in the file?
i know how to use <fstream> header and its components but how do you insert this into a file, ensurng that only two bits are used to represent the character? an explanation and example would be good.
thank you in advance.
AnswerInput-output of a bit field directly is not a good idea; there are implementation-dependencies (ordering of members, endianness, size etc). The portable way to do this is to convert the bits to a string containing '0' and '1' chars for output; read the string and convert it back to the internal representation of the bits for input.
std::bitset<> makes this painless. See:
http://cplusplus.com/reference/stl/bitset/
struct dante { unsigned jey : 2 ; } vergil ;
int main()
{
vergil.jey = 2 ;
// output
std::cout << std::bitset<2>(vergil.jey) << '\n' ;
// input
std::string bits ;
std::cin >> bits ;
vergil.jey = std::bitset<2>(vergil.jey).to_ulong() ;
}