/* raFileIO.cpp Name: CIS 150 Random access (binary) file I/O lab Date: Lab to demonstrate binary file reading and writing. */ // Finish the parts of the program marked ** TODO ** // A separate data file named pres.txt should also be downloaded. #include #include #include #include #include using namespace std; class President { private: static const int NAME_SIZE = 39; int year; char name[NAME_SIZE+1]; public: President() { setYear(0); setName(""); } President(int yr, string nm) { setYear(yr); setName(nm); } void setYear(int yr) { year = yr; } void setName(string nm) { if (nm.length() > NAME_SIZE) nm.resize(NAME_SIZE); nm.copy(name, nm.length()); name[nm.length()] = '\0'; } int getYear() const { return year; } string getName() const { return string(name); } }; bool displayFile(string filename); int main(int argc, char** argv) { string fname = "pres.dat"; string pres44 = "Barack Obama"; string pres45 = "Donald Trump"; int year44 = 2009; int year45 = 2016; cout << "Before adding last two presidents:\n"; bool ok = displayFile(fname); if (ok) { // ** TODO ** Part I // Open the file specified by fname for binary reading and writing // If file error, display error message and exit with failure status // Create a President object using year44 and pres44 // Create a President object using year45 and pres45 // Seek to the end of the file // Write both President records to the output file as binary data // Close the file // ** END OF TODO ** cout << "\nAfter adding last two presidents:\n"; displayFile(fname); } cout << "Press enter to continue..."; cin.get(); return 0; } bool displayFile(string filename) { long numRecs; President rec; // ** TODO ** Part II // Open the file specified by filename for binary reading // If file error, display error message and return false // Calculate the number of records and store in numRecs // For each record in file // Read a binary record from the file into rec // Display record number, ". ", name from record, " (", year from record, ")\n" // Close the file // ** END OF TODO ** return true; }