How can I serialize a struct into a file in the style of C?
Mike Parker via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jul 21 19:11:27 PDT 2017
On Saturday, 22 July 2017 at 01:45:29 UTC, solidstate1991 wrote:
> Due to it's convenience, I was thinking on reading and writing
> file headers by creating structs mirroring the layouts of
> actual headers I would need. I've seen many examples of this in
> C, however I' struggling using the same methods through the use
> of code.stdc.stdio, especially as I can't really trace bugs
> from fread.
struct Data {
int x;
float y;
ubyte z;
}
void main() {
import core.stdc.stdio;
Data od = Data(10, 3.0f, 5);
FILE* fp = fopen("data.dat", "wb");
size_t ret = fwrite(&od, od.sizeof, 1, fp);
fclose(fp);
assert(ret == 1);
Data id;
fp = fopen("data.dat", "rb");
ret = fread(&id, id.sizeof, 1, fp);
fclose(fp);
assert(ret == 1);
assert(id.x == 10);
assert(id.y == 3.0f);
assert(id.z == 5);
}
More information about the Digitalmars-d-learn
mailing list