Search code examples
windowsfileddmd

Read file byte by byte in D


How do I read a file byte by byte in D?

What I have is an open file, say:

auto f = File("test.bin");

Now I need to read bytes, say:

ubyte first = fgetc(f); // this is whishfull thinking
ubyte second = fgetc(f);

I'd also need to be able to do other stuff, like reading uints, ushorts, skipping (fseek) etc. for instance (C again):

fread(&third,2,1,fptr);

bonus question is if it is possible to read a struct in one go, say I have

struct Test { ubyte a,b,c; uint d,e;  /* etc */ }

can I read it from a binary file?


Solution

  • Phobos provides you with an excellent byChunk function for this purpose.

    You really do not want to read file by byte, but rather by chunk, and preferrably a chunk the same size as the page (typically 4 KiB).