#include #include #include class IP_Address { friend ostream &operator<<(ostream&, const *IP_Address); public: int n1, n2, n3, n4; }; ostream &operator<<(ostream &output, const IP_Address &ip) { output << ip.n1 << "." << ip.n2 << "." << ip.n3 << "." << ip.n4; return output; } class Member { friend ofstream &operator<<(ofstream&, const Member &m); public: void Display(void); void SetInfo(void); private: char Name[40]; char Handle[40]; IP_Address IP; int Age; float Score; }; ofstream &operator<<(ofstream &output, const Member &m) { output.write((const char*)(&m), sizeof(Member)); return output; } int ClearError(istream& isIn) // Clears istream object { streambuf* sbpThis; char szTempBuf[20]; int nCount, nRet = isIn.rdstate(); sbpThis = isIn.rdbuf(); // Get streambuf pointer nCount = sbpThis->in_avail(); // Number of characters in buffer if ((nRet) || (nCount)) { // Any errors or characters left? isIn.clear(); // Clear error flags while (nCount) { // Extract them to szTempBuf if (nCount > 20) { sbpThis->sgetn(szTempBuf, 20); nCount -= 20; } else { sbpThis->sgetn(szTempBuf, nCount); nCount = 0; } } } return nRet; } void Member::SetInfo(void) { ClearError(cin); cout << "Please enter handle: "; cin.getline(Handle, 40); cout << "Please enter name: "; cin.getline(Name, 40); cout << "Please enter age: "; cin >> Age; cout << "Please enter score: "; cin >> Score; cout << "Please enter your IP numbers: "; cin >> IP.n1 >> IP.n2 >> IP.n3 >> IP.n4; } void Member::Display(void) { cout << "Handle: " << Handle << endl; cout << "Name: " << Name << endl; cout << "IP: " << IP << endl; cout << "Age: " << Age << endl; cout << "Score: " << setiosflags(ios::fixed | ios::showpoint) << Score << endl; } void PrintNth(int n, ifstream &fp) { Member temp; fp.seekg(n * sizeof(Member)); fp.read((char*)(&temp), sizeof(Member)); temp.Display(); } void main(void) { Member temp; cout << "Member is " << sizeof(Member) << " bytes long." << endl << endl; ofstream outBin("output.bin", ios::out); temp.SetInfo(); outBin << temp; temp.SetInfo(); outBin << temp; temp.SetInfo(); outBin << temp; cout << endl << "Closing file" << endl << endl; outBin.close(); cout << endl << "Opening file" << endl << endl; ifstream inBin("output.bin", ios::in); cout << "Entry 1" << endl; PrintNth(1, inBin); cout << endl << "Entry 0" << endl; PrintNth(0, inBin); cout << endl << "Entry 2" << endl; PrintNth(2, inBin); inBin.close(); }