CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Feb 2006
    Posts
    15

    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?

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725

    Re: Sorting binary files

    It is difficult to follow your code without code tags. Please
    see the FAQ concerning adding code tags so that there will
    be proper indentation.

    You are opening the file with the mode : in | out | binary

    I think the file must already exist if you use that mode.
    Does the file exist ? If not, all of the writes/reads failed.

  3. #3
    Join Date
    Feb 2006
    Posts
    15

    Re: Sorting binary files

    Sorry for tags, I will see the FAQ.

    Yes, the file exists, and reading and writing succeeds, just not the right numbers are written..

  4. #4
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725

    Re: Sorting binary files

    After the f.seekp() , try outputting the value of f.tellp() to
    verify that it is correct.

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
  •  





Click Here to Expand Forum to Full Width

Featured