Suppose you get appointed in a company under HR department. You have assigned a file “Employee.dat” which contains information of all employees joined in year 2000 in binary format. Your manager assigned you two tasks. A) Search a specific employee information with respect to its sequence number in file. B) Add more employee’s data in the same file at the end(as many as the manager would want to) write the code to complete both tasks in your main() function. You don't need to create the Employee structure, suppose the structure employee is already created with data members and set get functions.
write code in c++
#include <iostream>
#include <fstream>
#include <vector>
int main()
{
ifstream fin;
fin.open("Employee.dat");
if (!fin) {
cerr << "Error in opening the file" << endl;
return 1;
}
vector<Employee> people;
Employee temp;
while (fin >> temp.number >> temp.name >> temp.surname >> temp.years) {
people.push_back(temp);
}
// now print the information you read in
for (const auto& person : people) {
cout << person.name << ' ' << person.surname << ' ' << person.years << endl;
}
int number_to_search = 5;
std::vector<Employee>::iterator it = std::find_if(people.begin(), people.end(), [=](const Employee& emp){emp.number == number_to_search; });
cout<<it->name<<endl;
ofstream file_obj;
// Opening file in append mode
file_obj.open("Employee.dat", ios::app);
// Object of class contestant to input data in file
Employee obj;
// Feeding appropriate data in variables
string str = "Michael";
string surname = "Jackson";
int age = 18, number = 2500;
// Assigning data into object
obj.name = str;
obj.years = age;
obj.number = number;
// Writing the object's data in file
file_obj.write((char*)&obj, sizeof(obj));
return 0;
}
Comments
Leave a comment