Writing Classes to File

BCS BCS at pathlink.com
Mon May 8 09:59:15 PDT 2006


Jeremy wrote:
> Is there a way I can just write a whole class to a file?
> 
> For example, why can't I do:
> 
> file.writeExact(someClass, someClass.sizeof);
> 
> This seems to just write 4 bytes, which must be the pointer.
> 
> The compiler complains when I do this:
> 
> file.writeExact(*someClass, (*someClass).sizeof);
> 
> Saying that '*' is only used infront of pointers -- but aren't class always
> represented with pointers?
> 
> Anyway, I want to save a class to file, so I can load it back. I was hoping
> there was a way to do this without having to write/read each element of the
> class seperately.
> 
> 
My solution is to declare a struct that has related data members in it. 
Then I give the class a DumpToFile method (generally named something 
else) that copies the data to the struct and does the writeExact thing. 
A readExact and revers translation do the other end. This has the 
advantage of providing a nice place to do some translations like endean 
swaps and recursive decent of trees (dump each child, recording where it 
is, place a FILE pointer in the struct and then dump the struct).

The biggest catch is keeping the struct<->class translators up to date 
with new rev of the class.

<script:coffee author.GetOn(SoapBox);)>

But that beings up my old dead horse: the "witheach" statement
http://www.digitalmars.com/d/archives/digitalmars/D/32232.html

<script:coffee author.GetOff(SoapBox);)>



More information about the Digitalmars-d mailing list