For stuff like this, you usually use a code generator. Let's assume the source looks like this:
struct a {
int i;
}
struct b {
string name;
struct a a;
}
What you do is you write a simple parser which searches the source (probably some header file) for "struct", then you read the name of the struct (anything between "struct" and "{"). Write this to the output:
cout << "struct " << name << " * read_struct_" << name << " (stream in) {" << NL
<< " struct " << name << " * result = malloc (sizeof(struct " << name << "));" NL
parseFields (headerStream);
cout << " return result;" << NL << "}" << NL ; }
Note my C++ is a bit rusty so this probably doesn't compile but you should get the idea.
In parseFields, you read each line and split it into two parts: Anything before the last space (i.e. "int" in the first example) and the stuff between the last space and and the ";". In this case, that would be "i". You now write to the output:
cout << "read_" << fieldType << "(in, &result->" << fieldName << ");" << NL;
Note: You'll need to replace all the spaces ub the field type with "_".
In the output, this looks like so:
struct a * read_struct_a (stream in) {
struct a * result = malloc(sizeof(struct a));
read_int(in, &result->i);
return result;
}
This allows you to define how to read or write an int somewhere else (in a utility module).
Now, you have code which reads the structure definitions from a header file and creates new code that can read the structure out of some stream. Duplicate this to write the structure to a stream. Compile the generated code and you're done.
You will also want to write unit tests to verify that the parsing works correctly :) Just create a structure in memory, use the write methods to save it somewhere and read it back again. The two structures should be identical, now. You will want to write a third code generator to create code to compare two structures.