Write struct to file
Andrej Mitrovic
andrej.mitrovich at gmail.com
Sat Feb 25 10:33:54 PST 2012
Well first I'd recommend not allocating the struct on the heap. Then you can do:
import std.stdio;
struct nagger
{
string name;
int age;
double weight;
string msg;
}
void main()
{
nagger lal;
lal.name = "name";
lal.age = 23;
lal.weight = 108.5;
lal.msg = "msg";
auto file = File("test.bin", "w");
auto writeBytes = fwrite(&lal, byte.sizeof, lal.sizeof, file.getFP());
file.close();
nagger dup;
file = File("test.bin", "r");
auto readBytes = fread(&dup, byte.sizeof, dup.sizeof, file.getFP());
assert(lal == dup);
}
This doesn't work for heap-allocated structs.
More information about the Digitalmars-d-learn
mailing list