A bit of binary I/O

Heinz billgates at microsoft.com
Sat Jan 20 14:49:24 PST 2007


Hi guys, i'm having great fun writing and reading binary files. It's my first time doing this and i've got a few questions in mind.
I write the same data(1 ulong and 1 string, i call them primitives) in 3 different ways and i get a different output for one of them. I create 1 file per method. If you open the created file with an hex editor you can see this.

The first way is to write primitives manually one by one:

// primitive way
ulong i = 9;
char[] s = "hello world";
myFile.writeExact(&i, i.sizeof);
myFile.writeExact(&s, s.sizeof);

Reading data:
// Is done by reading each primitive.
ulong i2; char[] s2;
myFile.readExact(&i2, i2.sizeof);
myFile.readExact(&s2, s2.sizeof);



The second way is to write a structure with all the primitives as members:

// struct way
struct t
{
	ulong i;
	char[] s;
}

t mt;
mt.i = 9;
mt.s = "hello world";
myFile.writeExact(&mt, mt.sizeof);

Reading data:
// We read the entire struct.
t mt2;
myFile.readExact(&mt2, mt2.sizeof);



And the third way is to write a class with all the primitives as members:

// class way
class tt
{
	ulong i;
	char[] s;
}

tt mtt = new tt();
mtt.i = 9;
mtt.s = "hello world";
ResFile.writeExact(&mtt, mtt.sizeof);

Reading data:
// We read the entire class.
tt mtt2;
myFile.readExact(&mtt2, mtt2.sizeof);



All of these methods works perfect. I'm able to retrieve values from all of them. Now lets check at the outputs:

// Primitive

09 00 00 00 00 00 00 00 0B 00 00 00 A0 C7 41 00

// Structure

09 00 00 00 00 00 00 00 0B 00 00 00 A0 C7 41 00

// Class

C0 3F 91 00

My questions are:

1) What's the best method to write data (in terms of data protection/encryption against reversion). The class way seems to me at first look the most secure way.
2) Wich method is the faster in retrieving data?
3) How the hell does this work? I mean, the string s is 10 chars long but the first 2 methods uses only 8 bytes to store the string and most of them are 0. Even more interesting, look at the class method, it uses only 4 bytes to store about 18 bytes of real data! WTF.
I'm really ?

This is a very interesting subject to me and if someone could clear my mind i would apreciate it very much.

Thx you very very much in advance.

Heinz



More information about the Digitalmars-d-learn mailing list