Alex Rivera | Logout

dumping c++ structures to a text file

Asked 2009-02-27T01:50:17.223
9

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

Edit
Report

1 Answer

6

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.

answered 2009-02-27T01:55:37.647

Your Answer