Write struct to file

Andrej Mitrovic andrej.mitrovich at gmail.com
Sat Feb 25 10:36:34 PST 2012


On 2/25/12, Andrej Mitrovic <andrej.mitrovich at gmail.com> wrote:
> This doesn't work for heap-allocated structs.
>

Sorry my bad. .sizeof should always be set on Types and not variable
names, because a struct pointer will have sizeof == size_t, whereas a
simple struct variable will have sizeof equal to the struct size. So
it can work just fine with heap-allocated structs:

void main()
{
    auto lal = new nagger();
    lal.name   = "name";
    lal.age    = 23;
    lal.weight = 108.5;
    lal.msg    = "msg";

    auto file = File("test.bin", "w");
    auto writeBytes = fwrite(cast(void*)lal, byte.sizeof,
nagger.sizeof, file.getFP());
    file.close();

    nagger dup;
    file = File("test.bin", "r");
    auto readBytes = fread(&dup, byte.sizeof, nagger.sizeof, file.getFP());

    assert(dup == *lal);
}


More information about the Digitalmars-d-learn mailing list