Reading file as binary

baws blaquee at gmail.com
Wed May 29 15:03:23 PDT 2013


Im trying to learn D, lovely language for a C++ lover. I have a 
file Im trying to parse, but I need to read the contents as 
binary data. I also need help understanding how read() works. I'd 
like to read the first four bytes which identify the file header, 
I need it to show as a sequence of bytes, how can i output the 
first 4 bytes to show like 0xFFCF?

With my code, im getting the integer values, If i use 
cast(byte[]) on read and writefln("Reading header info: 0x%x", 
bytesRead[0]);

Ill only get the first byte 0xCF.


import std.stdio;
import std.file;
import std.array;

struct xsdhead{
     int head1;
     int head2;
     int numTables;
};

immutable int headerInfo1 = 0xFFCF;
immutable int headerInfo2 = 0x0002;

int main(string [] args){
     writeln("start");
     if(args[1] == null){
         writeln("pass a file");
         return 0;
     }
     auto file = args[1];
     writeln("Working on ", file);

     auto bytesRead =  cast(byte[]) read(file, 4);
     writefln("Reading header info: %s", bytesRead);
     writefln("Address of caret is: 0x%X", &bytesRead);

     return 0;
}


More information about the Digitalmars-d-learn mailing list