Using array slices with C-style fread() from file

tetyys via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 21 11:58:58 PDT 2017


On Wednesday, 21 June 2017 at 18:49:01 UTC, uncorroded wrote:
> Is there a way of making this work with D slices? Can they be 
> used as C-style pointers?

What about this:

@nogc ubyte[n] rand_bytes(uint n)() {
     import core.stdc.stdio;
     FILE *fp;
     fp = fopen("/dev/urandom", "r");
     ubyte[n] buf;
     uint bread = 0;
     while (bread < n) {
         auto toread = n - bread;
         auto read = fread(buf[bread .. $].ptr, ubyte.sizeof, 
toread, fp);
         bread += read;
     }
     fclose(fp);
     return buf;
}

?


More information about the Digitalmars-d-learn mailing list