I’ve decided to add file IO to my railroad game program. As always, every thing I do requires some new way to look at things. MFC provides serialization and I’m using MFC at the moment. The program only uses it for the user interface until now.
Serialization is a way to have each object know how to read and write itself. The MFC serialization seems simple enough and each object would just know how to read and write itself. The two issues that made this seem unworkable to me are:
1. I want to use XML so that I can examine my files to make sure that there are no file output bugs.
2. I have data structures that have data stored in memory and maintained with pointers.
The data structure pointer issue can be solved by keeping an ID associated with every item. When an item is written, the ID is what is written. When it is read, the ID is read and the pointer is useless until some other code does a search of the items in memory and finds one with the correct ID. The pointer is then fixed. This is painful because it’s extra code in many places that just seems to bypass the simplicity of having each item serialize itself. The parent item must know about it’s children. I had to solve this regardless of using MFC serialization or not and it is used in those cases where it is required.
The XML issue is a bit trickier. The MFC serialization seems to expect the objects themselves to know how much data to read. I’ll need to investigate the MFC serialization code a bit more and learn how this is handled when the objects can have a variable number of children. Then there is the issue of end tags. Do I find a start tag then search through the data one character at a time until I’ve found the child tag count? Do I then call the child object serialization code and let it deal with the child tag and then figure that the file pointer is in the right place to find the end tag once the children are serialized?
Now the important part. This is really part of issue 1 above but it very important. I don’t wan’t to have the object code parse the XML data just for that object. I want to have a parser that is separate code deal with it. How do I do that while still using the serialization of MFC? The MFC serialization passes around what is essentially a file handle. I need XML node pointers with child nodes, etc…
I’ll give it some thought. Maybe I can use a scheme where each object uses the XML parser to parse just the one object. Then I could even embed XML into an otherwise binary output file and it would probably work fine. This is some good food for thought because I’m not happy yet with my file IO code.