Writing Classes to File

Jeremy Jeremy_member at pathlink.com
Mon May 8 11:04:43 PDT 2006


In article <e3ntd5$1nnb$1 at digitaldaemon.com>, BCS says...
>
>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);)>

So, could you just include the struct inside your class?

e.g.:

struct ClassVars {
int x, y;
int health;
};

class someClass {
private:
ClassVars myVars;
..
public:
void saveTo(BufferedFile someFile) {
someFile.writeExact(&myVars, myVars.sizeof);
}
};

And in processing that class (e.g. did this character gain some health) -- you
could check myVars.health etc.





More information about the Digitalmars-d mailing list