Write struct to file

Ali Çehreli acehreli at yahoo.com
Sun Feb 26 16:13:11 PST 2012


On 02/26/2012 03:22 PM, Chopin wrote:

 > I don't want to hear the reinvent the wheel :(, I think you
 > learn a lot by doing thing like this.

Agreed.

 > So, when I POST a blog-entry, I will read it, and write it to a file. I
 > don't want write strings in a file, like:
 >
 > 1--||--Title--||--The entry--||--Date

I encourage you to stay with human-readable formats unless there is a 
reason not to. You can ditch XML, fine, but consider other formats like 
json. :) But I understand that you want to do this to learn. Fine...

 > I have little knowledge about system programming, and writing raw files.
 > But my dream was like:
 >
 > SOME_INT_WITH_LENGTH_OF_STRUCT_TO_THE_RIGHT HERE_IS_THE_RAW_STRUCT
 > SOME_INT_WITH_LENGTH_OF_STRUCT_TO_THE_RIGHT HERE_IS_THE_RAW_STRUCT
 > etc.etc.etc.

You can do that only with structs that contain the entire data. As soon 
as there is a reference member, you must dereference that member to grab 
that member's data. For example, when you have strings, slices, 
associative arrays, class variables, pointers, and other user types with 
reference semantics, the data is not within the struct itself.

No matter how long the string is, the following struct is always the 
same size:

struct S
{
     char[] s;
}

On the other hand, the following is fine for what you want to do:

struct S
{
     char[1000] s;
}

But is 1000 always enough? Is it wasteful (every instance of S will be 
very large.)?

 > Then read those structs in array :)

Again, that part is easy as long as the struct doesn't have reference 
members.

 > I thought this was kinda easy in C, but I could be very wrong!

C has exactly the same issues. As soon as you have a pointer member you 
must /follow/ that member to reach the actual data.

 > So I
 > thought it must be super easy in D! I don't have the knowledge...

D is awesome compared to C as it enables serializing/deserializing data 
with its generic programming and compile-time reflection features like this:

   http://dlang.org/traits.html#allMembers

I don't know their details but I would imagine that serialization 
libraries must be written taking advantage of allMembers.

 > ae.utils.json <-- this will be not as "cool" as writing it raw binary? :p

Must be subjective. I find json output cooler that binary. :p

Ali



More information about the Digitalmars-d-learn mailing list