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..
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';
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With