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:22:53 PDT 2017


On Saturday, 22 July 2017 at 02:11:27 UTC, Mike Parker wrote:
> 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);
> }

I should add, though, that you're better off using either 
std.stdio.File or std.file. Use the former if you need to make 
multiple reads/writes to a file, the latter if you can pull it in 
or push it out all in one go. They take arrays as arguments, so 
if you have something like Data[], you can pass it directly to 
the appropriate functions. To write a single instance, you'll 
have to take the pointer and slice it. Either way, it's less 
code, less error prone, and more idiomatic than using the C API.


More information about the Digitalmars-d-learn mailing list