SA3_2101053_DSA4
SA3_2101053_DSA4
- 3
INPUT :
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
class Employee
{
private:
char name[50];
int ID;
char Designation[50];
int Salary;
public:
void get_data()
{
cout << "Enter name of employee: ";
cin.ignore();
cin.getline(name, 50);
cout << "Enter employee Id: ";
cin >> ID;
cout << "Enter designation of employee: ";
cin.ignore();
cin.getline(Designation, 50);
cout << "Enter salary of employee: ";
cin >> Salary;
}
void display()
{
cout << "Name: " << name << endl;
cout << "Id: " << ID << endl;
cout << "Designation: " << Designation << endl;
cout << "Salary: " << Salary << endl;
}
void add()
{
ofstream file1, file2;
Employee E;
E.get_data();
file1.open("Employee.txt", ios::binary | ios::app);
if (!file1) {
cout << "Error opening file Employee.txt!" << endl;
return;
}
file2.open("Indexed.txt", ios::binary | ios::app);
if (!file2) {
cout << "Error opening file Indexed.txt!" << endl;
return;
}
file1.write((char*)&E, sizeof(E));
int num = E.ID;
file2.write((char*)&num, sizeof(num));
file1.close();
file2.close();
}
void read()
{ Employee e;
ifstream datafile, indexfile;
datafile.open("Employee.txt", ios::binary);
indexfile.open("Indexed.txt", ios::binary);
if (!datafile || !indexfile) {
cout << "Error opening files!" << endl;
return;
}
cout << "\n Data from Employee File: " << endl;
while (datafile.read((char*)&e, sizeof(e)))
{ e.display();
}
datafile.close();
cout << "\n Data from Index File: " << endl;
int empID;
while (indexfile.read((char*)&empID, sizeof(int)))
{ cout << "Employee ID: " << empID << endl;
}
indexfile.close();
}
int get_ID()
{
return ID;
}
void search(int ID)
{
ifstream file1;
file1.open("Employee.txt", ios::binary);
if (!file1) {
cout << "Error opening file Employee.txt!" << endl;
return;
}
Employee E;
bool found = false;
while (file1.read((char*)&E, sizeof(E)))
{
if (E.get_ID() == ID)
{
E.display();
found = true;
break;
}
}
if (!found)
cout << "Employee with ID " << ID << " not found." << endl;
file1.close();
}
void delete_employee(int ID)
{
ifstream file1, file3;
ofstream file2, file4;
file1.open("Employee.txt", ios::binary);
if (!file1) {
cout << "Error opening file Employee.txt!" << endl;
return;
}
file2.open("Employeetemp.txt", ios::binary | ios::app);
if (!file2) {
cout << "Error opening file Employeetemp.txt!" << endl;
return;
}
file3.open("Indexed.txt", ios::binary);
if (!file3) {
cout << "Error opening file Indexed.txt!" << endl;
return;
}
file4.open("Indexedtemp.txt", ios::binary | ios::app);
if (!file4) {
cout << "Error opening file Indexedtemp.txt!" << endl;
return;
}
Employee E;
int num;
case '3':
cout << "Enter ID to search: ";
cin >> ID;
E1.search(ID);
break;
case '4':
cout << "Enter ID to delete: ";
cin >> ID;
E1.delete_employee(ID);
break;
case '5':
cout << "Exiting..." << endl;
return 0;
default:
cout << "Invalid choice!" << endl;
}
}
return 0;
}
OUTPUT :