Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

Writing a struct to a file

Moderators: larsivi kris

Posted: 11/06/07 04:07:13


I'm just about going crazy here. All I want to do is take an instance of a struct and write it to a FileConduit; sounds pretty simple, but Conduit.write() can only take void arrays. Now of course I could probably set up a new array and copy the contents of the struct into it, but that's both longwinded and inefficient. Nor do I want to implement an IWritable interface for my struct or anything esoteric like that.

Why is there no overload for Conduit.write() which simply takes a void* and a size? And what's the canonical approach to solving my problem with the minimum amount of fuss?


Author Message

Posted: 11/06/07 04:25:59 -- Modified: 11/06/07 04:28:24 by

well, if all you need is a void* and a size, then write(void[]) is your answer. Something like this ought to work:

write ((cast(void*) &struct)[0..struct.sizeof]);

See what that does? It makes a void[] from a pointer and a slice. There are other ways to do something similar, but this one is a common D idiom, and quite useful :)

Another approach would be to write each attribute/field individually, using perhaps a DataStream:

auto stream = new DataOutput(new FileOutput("myfile"));
stream.writeInt (struct.x);
stream.writeByte (struct.y);

The above will also flip bytes for you, if you configure DataOutput to do so. Hope that helps?

Posted: 11/06/07 12:56:28

Thanks a lot, that first one looks very much like what I was looking for. I'll have to try that out immediately. (I'm still pretty new to D, so I wasn't sure whether something like that could work.) How much runtime overhead is associated with that idiom?

Anyway, I'll probably try to wrap it in a template; that syntax is quite convoluted...

Posted: 11/06/07 17:33:33

overhead? perhaps 3 or 4 assembler instructions (when -O and -release are applied). There's no copying involved, if that's what you mean ... slices are true aliases onto existing content, and represent one of the best features of D

Posted: 11/06/07 22:22:03

you might also find some utility in ...