Write struct to file

Andrej Mitrovic andrej.mitrovich at gmail.com
Sat Feb 25 15:08:01 PST 2012


On 2/25/12, Andrej Mitrovic <andrej.mitrovich at gmail.com> wrote:
> I'm not sure where you're getting that from:

Let that be a classic lesson on what never to do. Here's a
demonstration on how wrong I was:

import std.stdio;

struct Foo
{
    char[] name;
}

void main(string[] args)
{
   if (args[1] == "write")
   {
       Foo foo;
       foo.name = new char[](16);
       foo.name[] = 'a';
       writeln(foo);

       auto file       = File("test.bin", "w");
       auto writeBytes = fwrite(&foo, byte.sizeof, foo.sizeof, file.getFP());
   }
   else
   if (args[1] == "read")
   {
       Foo foo;
       auto file = File("test.bin", "r");
       auto readBytes = fread(&foo, byte.sizeof, foo.sizeof, file.getFP());
       writeln(foo);
   }
}

$ D:\dev\code\d_code>test write
Foo("aaaaaaaaaaaaaaaa")

$ D:\dev\code\d_code>test read
Foo(x"D8 6E 43 00 01 00 00 00 08 00 00 00 90 A0 42 00"c)

:)

To OP: If you want to serialize I recommend ae's json module
(ae.util.json) from https://github.com/CyberShadow/ae . There's also
Orange but it's based on xml and seems to be buggy the last time I've
tried it.


More information about the Digitalmars-d-learn mailing list