I have made a database kind of stuff. Problem I am facing is when i try to print whole database(list_employee function marked in colour),last record is printed twice.If I have opened new file without adding anything,then I get some garbage result.I have spend around 5 to 6 hour but could not find it.Please help.
Code:
class employee
{
private:
fstream empfile;
char name[40];
int age;
float bs;
void add_to_file();
void search_from_file(char* emp_name);
public:
employee(char *filename);
void add_employee();
void edit_employee();
void del_employee();
void list_employee();
~employee(){empfile.close();}
};
employee::employee(char *filename)
{
empfile.open(filename,ios::binary|ios::ate|ios::in|ios::out);
if(!empfile)
{
cout<<"Error opening file\nPress any key to exit...";
getch();
exit(0);
}
}
void employee::add_to_file()
{
empfile.write((char*)&this->name,sizeof(employee)-sizeof(ifstream));
empfile.clear();
}
void employee::add_employee()
{
cout<<"name..."; cin.getline(name,40);
cout<<"Age..."; cin>>age;
cout<<"Basic Salary..."; cin>>bs;
empfile.seekp(0,ios::end);
add_to_file();
}
void employee::list_employee()
{
empfile.seekg(0,ios::beg);
while(empfile)
{
empfile.read((char*)(&this->name),sizeof(employee)-sizeof(ifstream));
cout<<"Name..."<<name<<endl;
cout<<"Age..."<<age<<endl;
cout<<"Basic Salary..."<<bs<<"\n\n";
}
empfile.clear();
}
int main()
{
employee niec("c:\\windows\\desktop\\employee.dat");
int opt;
while(1)
{
clrscr();
cout<<"1.Add employee\n2.Edit Employee\n3.List Employee\n4.Exit";
cout<<"\nEnter your option...";
cin>>opt;
cin.get();
switch(opt)
{
case 1:niec.add_employee();break;
// case 2:niec.edit_employee();break;
case 3:niec.list_employee();break;
case 4:niec.employee::~employee();
exit(0);
break;
}
cout<<"Press any key to continue....";
getch();
}
getch();
return(0);
}