You are here:

C++/saving a structure to a file.

Advertisement


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

Answer
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: 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() ;
}  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

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.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.