You are here:

C++/saving a structure to a file.


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

Input-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:

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() ;


All Answers

Answers by Expert:

Ask Experts




my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.


about 15 years or so

post graduate engineer

©2016 All rights reserved.