Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dumping c++ structures to a text file

how would one go about writing the contents of a structure in C++ to a text file? What I want to do is, say I have a structure called A, with data members A.one, A.two, and so on, and I want to write them out line by line into a text file, like so

Structure A
A.one = value
A.two = value ...

Structure B
B.one = value
B.two = value

Basically I want to make a dump.. Is there an easy way to do this? What's the best I/O method for this? CFile? iostream? Thanks.. Is there an easier way to dump all of the values of member data of a class?


EDIT: Crap, thanks guys..

like image 277
krebstar Avatar asked Feb 27 '09 01:02

krebstar


2 Answers

No reflection in C++, so you have to do it manually, eg (using iostream, for simplicty):

dump_A(std::cout, "A", a);

void dump_A(std::iostream& os, const char* name, A const& a)
{
    os << "Structure " << name << '\n'
       << name << ".one = " << a.one << '\n'
       << name << ".two = " << a.two << '\n';
}
like image 138
Simon Buchan Avatar answered Oct 30 '22 05:10

Simon Buchan


C++ isn't introspective. That is, it doesn't know anything about the contents of its structures. You have to use some sort of manual annotation or a reflection system to do this.

Of course, if you're OK with hardcoding information about the structures, you can dump the information with any I/O method.

For instance:

struct A
{
  int member1;
  char member2;
};

void PrintA (const A& a)
{
  std::printf ("member1: %d\n", a.member1);
  std::printf ("member2: %c\n", b.member2);
}

As you can see this is tedious because it requires intimate knowledge of the structure, and won't be updated automatically if the structure is changed. But the overhead of a reflection system to do this "properly" can be a disadvantage, especially if you're learning.

like image 43
Dan Olson Avatar answered Oct 30 '22 07:10

Dan Olson