File Handling Program
File Handling Program
#include<iostream>
#include<fstream>
#include<stdio.h>
class Employee
private:
int code;
char name[20];
float salary;
public:
void read();
void display();
int getEmpCode()
return code;
int getSalary()
return salary;
salary=s;
};
void Employee::read()
cin>>code;
cin.getline(name,20);
cin>>salary;
void Employee::display()
cout<<code<<" "<<name<<"\t"<<salary<<endl;
//global declaration
fstream file;
void deleteExistingFile()
{
remove("EMPLOYEE.DAT");
void appendToFille()
Employee x;
x.read();
file.open("EMPLOYEE.DAT",ios::binary|ios::app);
if(!file)
return;
file.write((char*)&x,sizeof(x));
file.close();
void displayAll()
Employee x;
file.open("EMPLOYEE.DAT",ios::binary|ios::in);
if(!file)
while(file)
if(file.read((char*)&x,sizeof(x)))
x.display();
file.close();
void searchForRecord()
//read employee id
Employee x;
int c;
int isFound=0;
cin>>c;
file.open("EMPLOYEE.DAT",ios::binary|ios::in);
if(!file)
return;
while(file)
if(file.read((char*)&x,sizeof(x)))
{
if(x.getEmpCode()==c)
cout<<"RECORD FOUND\n";
x.display();
isFound=1;
break;
if(isFound==0)
file.close();
void increaseSalary()
//read employee id
Employee x;
int c;
int isFound=0;
float sal;
cin>>c;
file.open("EMPLOYEE.DAT",ios::binary|ios::in);
if(!file)
{
cout<<"ERROR IN OPENING FILE \n";
return;
while(file)
if(file.read((char*)&x,sizeof(x)))
if(x.getEmpCode()==c)
cin>>sal;
x.updateSalary(x.getSalary()+sal);
isFound=1;
break;
if(isFound==0)
file.close();
//ascending order
void insertRecord()
Employee newEmp;
newEmp.read();
fstream fin;
file.open("EMPLOYEE.DAT",ios::binary|ios::in);
fin.open("TEMP.DAT",ios::binary|ios::out);
if(!file)
return;
if(!fin)
return;
while(file)
if(file.read((char*)&x,sizeof(x)))
if(x.getEmpCode()>newEmp.getEmpCode())
fin.write((char*)&newEmp, sizeof(newEmp));
}
fin.write((char*)&x, sizeof(x));
fin.close();
file.close();
rename("TEMP.DAT","EMPLOYEE.DAT");
remove("TEMP.DAT");
int main()
char ch;
deleteExistingFile();
do
int n;
cin>>n;
switch(n)
{
case 1:
appendToFille();
break;
case 2 :
displayAll();
break;
case 3:
searchForRecord();
break;
case 4:
increaseSalary();
break;
case 5:
insertRecord();
break;
default :
cout<<"Invalid Choice\n";
cin>>ch;
}while(ch=='Y'||ch=='y');
return 0;