I have a program that runs a bank management.It saves the created accounts in account.dat. For example these are the contents of the data file:
1001 felisilda s 5000
0002 smith s 3000
1212 johnson c 3200

I want the output to be sorted increasingly based on the bank account number, like this.
0002 smith s 3000
1001 felisilda s 5000
1212 johnson c 3200

here's the code for displaying:

void display_all()
{
    account ac;
    ifstream inFile;
    inFile.open("account.dat",ios::binary);
    if(!inFile)
    {
        cout<<"File could not be open !! Press any Key...";
        return;
    }
    cout<<"\n\n\t\tACCOUNT HOLDER LIST\n\n";
    cout<<"====================================================\n";
    cout<<"A/c no.      NAME           Type  Balance\n";
    cout<<"====================================================\n";
    while(inFile.read(reinterpret_cast<char *> (&ac), sizeof(account)))
    {
        ac.report();
    }
    inFile.close();
}

On Linux, Windows and other OSes I can do that sort with the sort commandline. No code required.

Why would a business code this when it's just a command away?

Comments
Good point

If the file you are reading from is not sorted, you'll want to set up a container for all these records. Vector seems like a good choice. You'll read them all into the vector, then print them all. You can use Vector's built-in sort function or you can write your own sort function, your choice. Since you're reading it in one record at a time, if you write your own sort function, I imagine the Insertion Sort would be the way to go. But my vote is to use Vector's sort. You would just need to write the comparison function, which in your case would be comparing via the account number.

See this link for vector and read this article.
http://www.cplusplus.com/reference/vector/vector/
http://www.cplusplus.com/articles/NhA0RXSz/

Your comparison function would be something like this top line, using the link above as the model.

bool sortByAccountNumber(const account &lhs, const account &rhs) { return lhs.accountNumber < rhs.accountNumber; }

vector<account> accounts;
while(inFile.read(reinterpret_cast<char *> (&ac), sizeof(account)))
{
    accounts.push_back(ac);
}
sort(accounts.begin(), accounts.end(), sortByAccountNumber);

I'm assuming that "read" line accurately reads the information into ac. It looks a little off compared to your file, but that's a separate topic and since you only asked about sorting/printing, I assume that part is under control. I don't know what your account structure looks like, but change sortByAccountNumber to match so it makes sense.

After the code above, accounts will be sorted by account number, then you can iterate through the vector and print by calling the report() function, which I guess displays the account information.

Edited 3 Months Ago by AssertNull