www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Using C's fread/fwrite with File objects

reply pineapple <meapineapple gmail.com> writes:
I'd like to use fread and fwrite in place of File.rawRead and 
File.rawWrite which force the creation of an array where I'd 
rather specify a buffer location and length. I'd like to do this 
using a File object but the handle for the C stream is a private 
member and I can't find any way to access it. Is there a getter 
or something I missed, or else some way to pry private data like 
this out of a class?
Oct 22 2015
next sibling parent pineapple <meapineapple gmail.com> writes:
Answered my own question: Turns out File.getFP() does exactly 
what I needed
Oct 22 2015
prev sibling next sibling parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 10/22/2015 11:20 AM, pineapple wrote:
 I'd like to use fread and fwrite in place of File.rawRead and
 File.rawWrite which force the creation of an array where I'd rather
 specify a buffer location and length.
Would you not create that buffer? :) If you already have a piece of memory, it is trivial to convert it to a slice in D: auto slice = existing_pointer[0 .. number_of_elements]; http://ddili.org/ders/d.en/pointers.html#ix_pointers.slice%20from%20pointer The operation is not expensive because D slices are nothing but a pointer and length. Ali
Oct 22 2015
parent pineapple <meapineapple gmail.com> writes:
On Thursday, 22 October 2015 at 18:28:50 UTC, Ali Çehreli wrote:
 If you already have a piece of memory, it is trivial to convert 
 it to a slice in D:

   auto slice = existing_pointer[0 .. number_of_elements];


 http://ddili.org/ders/d.en/pointers.html#ix_pointers.slice%20from%20pointer

 The operation is not expensive because D slices are nothing but 
 a pointer and length.

 Ali
Cool, I hadn't realized slices worked like that. Still, it was more convenient to use fread and fwrite in this case. I had an pointer where I wanted to be able to read and write one byte at a time and fread/fwrite are familiar and comfortable options to me.
Oct 22 2015
prev sibling parent John Colvin <john.loughran.colvin gmail.com> writes:
On Thursday, 22 October 2015 at 18:20:07 UTC, pineapple wrote:
 I'd like to use fread and fwrite in place of File.rawRead and 
 File.rawWrite which force the creation of an array where I'd 
 rather specify a buffer location and length.
D's arrays *are* just buffer locations and lengths with a few extra properties, methods and operators. T* ptrToBuffer = /* ... */; size_t lengthOfBuffer = /* ... */; T[] buffer = ptrToBuffer[0 .. lengthOfBuffer]; File f = /* ... */; T[] filledPartOfBuffer = f.rawRead(buffer); Note that at no point in the above is a new buffer allocated.
Oct 22 2015