10

How to read and write to binary files in D language? In C would be:


    FILE *fp = fopen("/home/peu/Desktop/bla.bin", "wb");
    char x[4] = "RIFF";

    fwrite(x, sizeof(char), 4, fp);

I found rawWrite at D docs, but I don't know the usage, nor if does what I think. fread is from C:

T[] rawRead(T)(T[] buffer);

If the file is not opened, throws an exception. Otherwise, calls fread for the file handle and throws on error.

rawRead always read in binary mode on Windows.

Pedro Lacerda
  • 1,098
  • 9
  • 23

2 Answers2

8

rawRead and rawWrite should behave exactly like fread, fwrite, only they are templates to take care of argument sizes and lengths.

e.g.

 auto stream = File("filename","r+");
 auto outstring = "abcd";
 stream.rawWrite(outstring);
 stream.rewind();
 auto inbytes = new char[4];
 stream.rawRead(inbytes);
 assert(inbytes[3] == outstring[3]);

rawRead is implemented in terms of fread as

 T[] rawRead(T)(T[] buffer)
    {
        enforce(buffer.length, "rawRead must take a non-empty buffer");
        immutable result =
            .fread(buffer.ptr, T.sizeof, buffer.length, p.handle);
        errnoEnforce(!error);
        return result ? buffer[0 .. result] : null;
    }
Scott Wales
  • 11,336
  • 5
  • 33
  • 30
  • What if your data is already in memory (received from an api call) instead of on disk? The Stream api doesn't support rawRead, and there's no file handle to pass to .fread ... – Jason Sundram Sep 23 '14 at 02:02
2

If you just want to read in a big buffer of values (say, ints), you can simply do:

int[] ints = cast(int[]) std.file.read("ints.bin", numInts * int.sizeof);

and

std.file.write("ints.bin", ints);

Of course, if you have more structured data then Scott Wales' answer is more appropriate.

Peter Alexander
  • 53,344
  • 14
  • 119
  • 168