C++ Program to find a particular person from a file using file handling.
1: #include <iostream>
2: #include <fstream>
3: using namespace std;
4:
5: /////////////////////////////////////////////////////////////////////////////////////////////////
6: class person{
7: protected:
8: char name[80];
9: short age;
10: public:
11: void getData(){
12: cout << "Enter name: "; cin.ignore(); cin.getline(name,80,'\n');
13: cout << "Enter age: "; cin >> age;
14: }
15: void showData(){
16: cout << "Name: " << name << endl;
17: cout << "Age: " << age << endl;
18: }
19: };
20: /////////////////////////////////////////////////////////////////////////////////////////////////
21: int main(){
22: person pers;
23: fstream fs("person.dat", ios::in | ios::out | ios::binary);
24: char opt;
25: do{
26: cout << "\nEnter person's data:\n";
27: pers.getData();
28: fs.write(reinterpret_cast<char*>(&pers),sizeof(person));
29: cout << "Any other person left? (y/n) "; cin >> opt;
30: }
31: while (opt == 'y');
32:
33: cout << "\n\nWhich person's data do you want to get? "; int n; cin >> n;
34: fs.seekg(0,ios::end);
35: int endPosition = fs.tellp();
36: int totalPersons = endPosition/sizeof(person);
37: cout << "Total Persons are: " << totalPersons << endl;
38:
39: fs.seekg((n-1)*sizeof(person));
40: fs.read(reinterpret_cast<char*>(&pers),sizeof(person));
41: pers.showData();
42:
43: return 0;
44: }
No comments:
Post a Comment