You are here:

C++/Sorting sequential file



I've written a sequential file that can create a file and adding data to it,i'm trying to write a member function that sort records of this file and according the sequential file i mentioned just one key for records and its :"ID"
could you give me a suggestion about sorting sequential file?
i know how to sort an array of data but now the datas are in a file
i think the solution is to put all the records to an array from the file that i have created and then sorting them according to the key,"ID", but i'm not sure about this idea and want your help for sorting records.

here is the code for just adding records to file:

using std::cout;
using std::cin;
using std::endl;
using std::ios;
using std::cerr;

using std::string;

using std::ofstream;

using std::exit;

class employment
  void ADD();
  int ID;
  char Fname[10];
  char Lname[10];
  char City[10];
  double Salary;

void employment::ADD()
  ofstream employee("c:\\tests.dat",ios::app);

     cerr<<"File could not be opened" <<endl;
  cout<<"Enter the ID,Fname,Lname,City and Salary."<<endl
     <<"Enter end-of-file to end input.\n?";

     employee<<ID<<' '<<Fname<<' '<<Lname<<' '<<City<<' '<<Salary<<endl;

int main()
  employment obj;


  return 0;


Hi dear Bita !

  What you have said is of course correct, sorting the contents inside (any) file is not an advisable approach if performance matter, better option is load the contents into main memory and perform sort which is more effective than sorting inside a file

With your case , load the contents into an object array eg

class empl
 int ID,
 char name[50],

void main()
  empl foo[20];

read the input file sequentially and load the object array with each index stores a record,
then preform sort over that object and list store the object is requires.

Get back to me for more queries
Thanks and Regards!
Prince M. Premnath  


All Answers

Answers by Expert:

Ask Experts


Prince M. Premnath


Years of research in C/C++ Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Feel free to query me :-)


More than 5 years


©2017 All rights reserved.