You are here:

C++/Sorting sequential file

Advertisement


Question
Hi

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:

#include<iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ios;
using std::cerr;

#include<string>
using std::string;

#include<fstream>
using std::ofstream;

#include<cstdlib>
using std::exit;

class employment
{
public:
  void ADD();
private:
  int ID;
  char Fname[10];
  char Lname[10];
  char City[10];
  double Salary;
};

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

  if(!employee)
  {
     cerr<<"File could not be opened" <<endl;
     exit(1);
  }
  cout<<"Enter the ID,Fname,Lname,City and Salary."<<endl
     <<"Enter end-of-file to end input.\n?";

  while(cin>>ID>>Fname>>Lname>>City>>Salary)
  {
     employee<<ID<<' '<<Fname<<' '<<Lname<<' '<<City<<' '<<Salary<<endl;
     cout<<"?";
  }

}
int main()
{
  employment obj;

  obj.ADD();

  return 0;
}


Thanx
Bita

Answer
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  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise

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

Experience

More than 5 years

Education/Credentials
MCA

©2016 About.com. All rights reserved.