// Object I/O by Chung // "this" pointer points to the object itself /* Sample Run Enter data for person: Enter name: chan Enter age: 1 Do another (y/n)? y Enter data for person: Enter name: jin Enter age: 2 Do another (y/n)? y Enter data for person: Enter name: chung Enter age: 3 Do another (y/n)? n Number of person objects in the file = 3 Enter Person Number(start from 0): 1 Name: jin Age: 2 Do another (y/n)? y Enter Person Number(start from 0): 5 No such person id Do another (y/n)? */ #include class person { protected: char name[40]; int age; public: void getData(void) { cout << "\n Enter name: "; cin >> name; cout << " Enter age: "; cin >> age; } void showData(void) { cout << "\n Name: " << name; cout << "\n Age: " << age; } bool readFF(int); // read from file void write2F(); // write to file static int howManyObj(); // return num of persons in file }; bool person::readFF(int pn) { // read person number pn from file if( pn > 0 && pn < howManyObj()) { ifstream infile; infile.open("PERSON.DAT", ios::binary); infile.seekg( pn*sizeof(person) ); infile.read( (char*)this, sizeof(*this) ); // read one person return true; } else { cout << "No such person id!"; return false; } } void person::write2F() { // write person to end of file ofstream outfile; outfile.open("PERSON.DAT", ios::app | ios::binary); outfile.write( (char*)this, sizeof(*this) ); } int person::howManyObj() { // return num of persons in file ifstream infile; infile.open("PERSON.DAT", ios::binary); infile.seekg(0, ios::end); // go to 0 bytes from end return (int)infile.tellg() / sizeof(person); // cal. num of persons } void main(void) { person p; // make an empty person char ch; do { // save persons to disk cout << "\nEnter data for person:"; p.getData(); // get data p.write2F(); // write to disk cout << "Do another (y/n)? "; cin >> ch; } while(ch=='y'); // until user enters 'n' int n = person::howManyObj(); // how many persons in file? cout << "Number of person objects in the file = " << n; do { cout << "\nEnter Person Number(start from 0): "; cin >> n; if(p.readFF(n)) p.showData(); cout << "\nDo another (y/n)? "; cin >> ch; } while(ch=='y'); // until user enters 'n' }