Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary file I/O

Tags:

io

d

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.

like image 772
Pedro Lacerda Avatar asked Oct 05 '10 02:10

Pedro Lacerda


2 Answers

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;
    }
like image 126
Scott Wales Avatar answered Nov 07 '22 11:11

Scott Wales


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.

like image 22
Peter Alexander Avatar answered Nov 07 '22 11:11

Peter Alexander