What is the D way to map a binary file to a structure?
mzfhhhh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Aug 30 18:01:31 PDT 2015
On Saturday, 29 August 2015 at 12:56:08 UTC, cym13 wrote:
> Hi,
>
> Let's say I have a simple binary file whose structure is
> well-known. Here is
> an example which stores points:
>
> struct Point {
> long x;
> long y;
> long z;
> }
>
> struct BinFile {
> uint magicNumber; // Some identifier
> ulong pointsNumber;
> Point[] points; // Array of pointsNumber points.
> }
>
> What is the best way to read some file and fill a structure
> with it? Would
> reading the file into a void[] and then casting it to the
> struct work with
> things like internal struct padding?
struct Point {
long x;
long y;
long z;
}
struct BinFile {
uint magicNumber; // Some identifier
ulong pointsNumber;
Point[] points; // Array of pointsNumber points.
this(ubyte [] buf)
{
auto f = cast(BinFile *)buf.ptr;
this = cast(BinFile)*f;
this.points =
(cast(Point*)&f.points)[0..cast(uint)this.pointsNumber];
}
}
More information about the Digitalmars-d-learn
mailing list