0

I have difficulty resolving one sort of simple task. The goal of the task is to combine two binary files into a third, and after the third file, sort in descending order. The resulting file will look something like this:

52,sdads

34,dsad

98,dasd

22,asdas

And I have to sort all these lines in descending order by the numbers. Please at least someone can tell how this can be implemented. What algorithm do I need to solve the problem, or help with what I need to start. I will be very grateful!

int main(){

    ofstream ofs("f3", ofstream::binary);
    ifstream ifs;

    ifs.open("f1", ifstream::binary);
    ifs.seekg (0, ifs.end);
    int len = ifs.tellg();
    ifs.seekg (0, ifs.beg);

    char * buffer = new char [len];
    ifs.read(buffer, len);
    ofs.write(buffer, len);
    ifs.close();
    delete[] buffer;

    ifs.open("f2", ifstream::binary);
    ifs.seekg (0, ifs.end);
    len = ifs.tellg();
    ifs.seekg (0, ifs.beg);

    buffer = new char [len];
    ifs.read(buffer, len);
    ofs.write(buffer, len);
    ifs.close();
    delete[] buffer;
}
Cfun
  • 8,442
  • 4
  • 30
  • 62
  • Did you read this question? https://stackoverflow.com/questions/16908671/c-sorting-binary-files Maybe this contains some helpful info – Dima Vak May 29 '20 at 19:25
  • 1
    The title says you want to sort a binary file, the text says it is a text file with lines. So what is the case? – Werner Henze May 29 '20 at 19:42
  • What exactly is your problem? Sorting? Or getting the number from each line? What do you believe should be done and what of this don't you know how to do? – Werner Henze May 29 '20 at 19:43
  • Use a `struct` or `class` to model a datum. Create a `std::vector`. Read the file into the vector. Sort vector. Write vector to file. – Thomas Matthews May 29 '20 at 20:08
  • My problem is to do something like 98, dasd 52, sdads 34, dsad 22, asdas. The file contains data in a column and I need to sort them by numbers from larger to smaller – Artemis Kungs May 29 '20 at 20:09
  • Thomas Matthews, okey,thank ty, ill try do something like this – Artemis Kungs May 29 '20 at 20:10
  • A binary file does not have the concept of lines. If its actually a binary file you will have to iterate byte by byte, breaking the datum into pieces based on size or line feed characters. To me it looks like you have a text file which you can sort using the linux utility sort. "sort -t, -nk1 mydata.file" will sort your data by number on the first comma separated value if the number is always the first. – jpsalm May 29 '20 at 20:32

0 Answers0