|
-
February 12th, 2009, 01:12 PM
#1
Sorting binary files
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?
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|