There's nothing wrong with straight-binary I/O, so long as you are strict about endian and size issues.
I think that your problem has to do with that pointer. It is useless to write a pointer to disk, because once your program terminates (if not before) it becomes meaningless.
jmc gave you the basic formula for the correct answer: Your binary file should look something like
First read the number of cars, then allocate enough memory, then read the car numbers.
1 2 3
|
f.read( (char*)&d.b, sizeof(int) ); // number of cars
d.c = new int[ d.b ]; // allocate space for all those cars
f.read( (char*)d.c, (sizeof(int) * d.b) ); // read them into memory
|
More about endian and size issues:
exception made a point about problems when using
istream::read(). If you want your code to work properly cross-platform, you need to explicityly define 1) byte-order (endianness) and 2) integer size.
So if you were to say that your file will be in network byte order (big-endian) and integers are four bytes, then you can write routines like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
int readint( istream& ins )
{
int result = 0;
char buf[ 4 ];
ins.get( buf, 4 );
if (ins)
for (int n = 0; n < 4; n++)
result = (result << 8) +buf[ n ];
return result;
}
int readints( istream& ins, int count, int* ints )
{
int n;
for (n = 0; ins && (n < count); n++, ints++)
*ints = readint( ins );
return n;
}
|
You can use them both handily:
1 2 3 4
|
d.b = readint( f );
if (!f) complain();
d.c = new int[ d.b ];
if (readints( f, d.b, d.c ) != d.b) complain();
|
etc.