A bit of binary I/O

janderson askme at me.com
Sat Jan 20 17:38:04 PST 2007


Heinz wrote:
> Chris Nicholson-Sauls Wrote:
> 
>> Heinz wrote:
>>> In C++ you can write an entire structure to a binary file:
>>>
>>> http://www.gamedev.net/reference/articles/article1127.asp
>>> http://www.codersource.net/cpp_file_io_binary.html
>>>
>>> Can you do the same in D?
>> Sure, and it will work between instances of the program so long as none of the structure's 
>> members are referances: pointers, object variables, arrays.
>>
>> -- Chris Nicholson-Sauls
> 
> So, you mean i can't have this structure because i has an array?
> 
> struct h
> {
> 
> }
> 
> Could you post an example please?

Right, because these arrays are essentially a pointer to data somewhere 
else, they don't exist in the same block of memory.

To do it automatically you would need some form of metadata (which would 
identify pointers) or something like serialization (which handled each 
element on its own).

In D and C++ you can read a block like below in one go:

struct h
{
   int x;
   int y;
   char a;
   char b[100];   //Note because this is constant its included in this 
block.
};

However you can't write something like this in D or C++:

struct h
{
   int x;
   int y;
   char a;
   char* b;  //This is pointing elsewhere in memory.  You'll need to fix 
this pointer up when you read it in.
};

Since D dynamic arrays are really:

struct Darray
{
    size_t length;
    T* type;      //Pointer to some location
};

You can't save these out inside a struct.  You need to save the data it 
points to as well.

-Joel


More information about the Digitalmars-d-learn mailing list