What it the preferred method to write a class to a file?

BCS BCS at pathlink.com
Tue Jul 25 12:43:56 PDT 2006


Charles D Hixson wrote:
> I'm thinking that I should build two methods, possibly
> called write and print where write would export a "binary"
> version of the class that is not intended to be human
> readable and print would export something with, e.g.,
> numbers translated into strings.
> 
> It appears as if the methods should be instance methods of
> the class.  It looks as if write should be implemented
> something like:
> void write(Stream stream)
> {  stream.writeExact(&this, this.sizeof);	}
> 
> Though probably in this version I'd want to include
> delimiters, a type id, and a length to facilitate writing
> the corresponding read routing (which would need to be a
> class method).
> 
> It this the best approach?  Also are there any suggestions
> as to a reasonable way to specify the type id, so that it
> would be the same from run to run?  Should I keep track of
> the ids myself (manually)?  If not, how would I know on an
> attempt to read which class the type id referred to?

I would define a struct that contains all of the trivial types and 
placeholders for the non trivial types (arrays would be replaced by an 
Array struct, etc.)

In the simple case all that is needed is to copy the elements into the 
struct and output it. If reference types are used, more complicated 
things need to be done. One option is to block out space for the struct 
and then output the referenced data (storing file pointers to the data 
in the struct), then backup and put the struct in the hole you left.

Referenced objects might still be an issue but they may be handled 
recursively (watch out for circular references).

Pulling data out of the file is much the same. I haven't tried anything 
like this with covariant classes. So I haven't any ideas on how to make 
that work.

This has the advantage over sterilization that the file can be navigated 
like the original data without having to walk the entire file.



More information about the Digitalmars-d-learn mailing list