Using array slices with C-style fread() from file
uncorroded via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jun 21 12:06:25 PDT 2017
On Wednesday, 21 June 2017 at 18:58:58 UTC, tetyys wrote:
> 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;
> }
>
> ?
Thanks a lot! That works. Did not know about the .ptr for a
slice. Is there any way of making the function with @safe as
well? I get the errors "cannot call @system function
'core.stdc.stdio.fread,fopen,fclose'.
More information about the Digitalmars-d-learn
mailing list