|
| 1 | +//person objects do disk IO |
| 2 | +#include<iostream> |
| 3 | +#include<fstream> |
| 4 | +using namespace std; |
| 5 | +class person |
| 6 | +{ |
| 7 | +private: |
| 8 | + char name[40]; |
| 9 | + int age; |
| 10 | +public: |
| 11 | + void getData() |
| 12 | + { |
| 13 | + cout << "\n Enter last name : " ; cin >> name; |
| 14 | + cout << "\n Enter age : " ; cin >> age; |
| 15 | + } |
| 16 | + void showData() |
| 17 | + { |
| 18 | + cout << "\n Name : " << name; |
| 19 | + cout << "\n Age : " << age; |
| 20 | + } |
| 21 | + void diskIn(int); |
| 22 | + void diskOut(); |
| 23 | + static int diskCount(); |
| 24 | +}; |
| 25 | +void person::diskIn(int pn) |
| 26 | +{ |
| 27 | + ifstream infile; |
| 28 | + infile.open("Person.dat",ios::binary); |
| 29 | + infile.seekg(pn*sizeof(person)); |
| 30 | + infile.read((char *)this,sizeof(*this)); |
| 31 | +} |
| 32 | +void person::diskOut() |
| 33 | +{ |
| 34 | + ofstream outfile; |
| 35 | + outfile.open("Person.dat",ios::app | ios::binary); |
| 36 | + outfile.write((char *)this,sizeof(*this)); |
| 37 | +} |
| 38 | +int person::diskCount() |
| 39 | +{ |
| 40 | +ifstream infile; |
| 41 | +infile.open("Person.dat",ios::binary); |
| 42 | +infile.seekg(0,ios::end); |
| 43 | +return (int)infile.tellg()/sizeof(person); |
| 44 | +} |
| 45 | +int main() |
| 46 | +{ |
| 47 | + person p; |
| 48 | + char ch; |
| 49 | + do |
| 50 | + { |
| 51 | + cout << "Enter data for person :: "; |
| 52 | + p.getData(); |
| 53 | + p.diskOut(); |
| 54 | + cout << "\nDo another (y/n)?"; |
| 55 | + cin >> ch; |
| 56 | + }while(ch=='y'); |
| 57 | + int n = person::diskCount(); |
| 58 | + cout << "\n There are " << n << " persons in file\n"; |
| 59 | + for(int j=0;j<n;j++) |
| 60 | + { |
| 61 | + cout << "\nPerson " << j; |
| 62 | + p.diskIn(j); |
| 63 | + p.showData(); |
| 64 | + } |
| 65 | + cout << endl; |
| 66 | + return 0; |
| 67 | +} |
| 68 | +/* |
| 69 | +Input: |
| 70 | +Enter data for person :: |
| 71 | + Enter last name : varad |
| 72 | + Enter age : 22 |
| 73 | +Do another (y/n)?y |
| 74 | +Enter data for person :: |
| 75 | + Enter last name : akshay |
| 76 | + Enter age : 19 |
| 77 | +Do another (y/n)?n |
| 78 | +
|
| 79 | +Output: |
| 80 | + There are 2 persons in file |
| 81 | +Person 0 |
| 82 | + Name : varad |
| 83 | + Age : 22 |
| 84 | +Person 1 |
| 85 | + Name : akshay |
| 86 | + Age : 19 |
| 87 | +*/ |
0 commit comments