Hi!

I can't understand anymore why isn't my binary file sorting working.

I have created a binary file, e.g., like this:

fstream f("myFile.txt",ios::in|ios:ut|ios::binary);
int n=3, a=2;
f.write((char*) &a,sizeof(int));
a=1; f.write((char*) &a,sizeof(int));
a=3; f.write((char*) &a,sizeof(int));

Now I want to sort the numbers without taking all the contents of the file into the memory - just by manipulating the file. So I write:

f.seekg(0,ios::beg);
int a1,a2;
for (int j=0;j<n-2;j++) {
f.seekg(sizeof(int)*j,ios::beg);
for (int i=j;i<n-1;i++) {
f.read((char*) &a1,sizeof(int));
f.read((char*) &a2,sizeof(int));
if (a1>a2) {
f.seekp(sizeof(int)*(-2),ios::cur);
f.write((char*) &a2,sizeof(int));
f.write((char*) &a1,sizeof(int));
}
f.seekg(sizeof(int)*(-1),ios::cur);
}
}

If I do the job on paper for this trivial example with only 3 numbers, I get the right result - 1, 2, 3. However, the program prints 3 3 3, when performing the printing:
f.seekg(0,ios::beg);
for (int i=1;i<=n;i++) {
f.read((char*) &a,sizeof(int));
cout<<a<<' ';
}

And I just can not get, where the problem is.. I tried to write just `-2` instead of `sizeof(int)*(-2)` and several other things but nothing works.. Can somebody explain it to me?