Search code examples
iod

Binary file I/O


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.


Solution

  • 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;
        }