reading a structure (eg header info) from file

Ali Çehreli acehreli at yahoo.com
Wed Jul 3 20:35:20 PDT 2013


On 07/03/2013 01:37 PM, captaindet wrote:

 > in C:
 >
 > typedef struct { /* info */ } INFO;
 > INFO info;
 > size_t checkio;
 > // read INFO from data file:
 > pf_datafile = fopen("datafile","rb");
 > checkio = fread((char *) &info, sizeof(info), 1, pf_datafile);

Just a reminder: The operation above is not portable. There are 
endianness and struct member padding issues.

 > how do i do this in D?

Assuming that the writer and the reader agree that it works, the closest 
in Phobos is std.stdio.rawRead.

 > the INFO struct might be anywhere in the file, not only at the beginning.

seek() does that.

import std.stdio;

struct Info
{
     size_t a;
     double b;
     byte c;
}

void main()
{
     auto info0 = Info(1, 2.25, 3);
     auto info1 = Info(4, 5.50, 6);

     writeTest("test_file", [ info0, info1 ]);
     readTest("test_file", 0);
     readTest("test_file", 1);
}

void writeTest(string fileName, const(Info)[] infos)
{
     auto file = File(fileName, "w");

     file.rawWrite(infos);
}

void readTest(string fileName, size_t index)
{
     auto file = File(fileName, "r");

     auto offset = index * Info.sizeof;
     file.seek(offset);

     // More than 1 would read as many elements
     auto info = new Info[1];
     file.rawRead(info);

     writefln("Read Info at index %s: %s", index, info);
}

Ali



More information about the Digitalmars-d-learn mailing list