Save/load data to a file

Derek Parnell derek at psych.ward
Sun Nov 16 13:52:47 PST 2008


On Sun, 16 Nov 2008 16:55:16 +0100, nobody wrote:

> I would like to be able to save and load a lot of data to/from a file. (in 
> D1)
> For example a struct like this:
> 
> struct Fruit
> {
>     int banana;
>     double[][] orange;
>     bool[] apple;
> }
> 
> Practically all the examples that I've come across only deal with saving and 
> loading text, so I'm having a hard time dealing with saving/loading 
> arrays/floats/bools/etc.
> 
> What would be a good way to do this?

It depends ... do you wish to save the data as a text representation or in
binary form?

Text takes up more room but can be more portable to different applications.

Binary is smaller and usually a lot faster.

For text output, you can format it using one of the popular styles, such as
XML, JSON, or CSV, or you can invent something more suitable to your
specific requirements. These generally require you to convert each piece of
data to a string and wrap that with 'start'/'end' markers.

For binary, you need to decide if 'endian'-ness is an issue or not. If you
are happy with the binary layout of the struct data in RAM and you can NOT
going to be using the data in other CPU architectures, then the simplest is
to just copy out the RAM bytes to disk. Of course, you have to add some
'structure' info to deal with the variable-length arrays but that can be as
simple as prefixing the data with the length value.


-- 
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell


More information about the Digitalmars-d-learn mailing list