How to read a C++ class from file into memory

Daniel Keep daniel.keep.lists at gmail.com
Thu Mar 22 23:27:10 PDT 2007



David Finlayson wrote:
> Jarrett Billingsley Wrote:
> 
>> "David Finlayson" <david.p.finlayson at gmail.com> wrote in message 
>> news:etvlr7$1a9p$1 at digitalmars.com...
>>
>>> Thanks for answering my post. Do you know how I might use std.stream to 
>>> read these files?
>> If you exactly how the data is structured, you may be able to define several 
>> structures which define the layout of the data, e.g.
>>
>> align(1) struct Header
>> {
>>     uint magic;
>>     uint version;
>>     char[100] comments;
>> }
>>
>> Or something along those lines, and then read it in with readExact:
>>
>> Stream s = ...
>> Header h;
>> s.readExact(&h, Header.sizeof);
>>
>> If the format is more complex, it'll probably take a bit more work, but 
>> that's the general idea. 
>>
> 
> OK, this is what I want. Question:
> 
> Header h creates a structure of type Header. Is h a pointer? It looks like you dereferenced it with &h in readExact(). I really don't understand how D uses pointers yet.

No, structs in D are POD: Plain Old Data.  &h is taking the address of h.

What readExact does is it takes a pointer, and a length, and reads
exactly that many bytes, and puts them at that pointer.  &h works out
*where* h is being stored (so readExact can write to it), and
Header.sizeof tells it how many bytes to read.

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/


More information about the Digitalmars-d-learn mailing list