C++/Sorting sequential file
Expert: Prince M. Premnath - 8/23/2009
QuestionHi
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
AnswerHi 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