/* Filename: sortemp.cpp Author: Br. David Carlson Date: June 13, 1998 Last Revised: February 21, 2013 This program sorts the emp.dat file that is created with the makeemp program. This sort program will not work for large files, as it uses an array to try to hold all of the data at once. Note that the sorting is done based on employee names, last name and then first name. Tested with: Microsoft Visual C++ 2008 g++ under Linux */ // iostream is indirectly included via emparray.h (and from there, employee.h) #include // needed for files #include "emparray.h" int LoadArray(fstream & InFile, EmpArrayType EmpArray, int & EmpCount); void WriteToFile(fstream & OutFile, EmpArrayType EmpArray, int EmpCount); int main(void) { EmpArrayType EmpArray; int Flag, EmpCount; fstream EmpFile, NewFile; EmpFile.open("emp.dat", ios::in | ios::binary); if (EmpFile.fail()) { cerr << "Could not open file emp.dat for input" << endl; exit(1); } Flag = LoadArray(EmpFile, EmpArray, EmpCount); EmpFile.close(); if (Flag == TooMuchDataFlag) cout << endl << endl << "The data would not fit in the array" << endl; else { SelectionSort(EmpArray, EmpCount); NewFile.open("emp.dat", ios::out | ios::binary); if (NewFile.fail()) { cerr << "Could not open file emp.dat for output" << endl; exit(1); } WriteToFile(NewFile, EmpArray, EmpCount); NewFile.close(); cout << endl << "Sorting completed. Press ENTER:" << endl; cin.get(); } return 0; } /* Given: InFile A binary file stream, already opened for input. Task: To read a sequence of employee data from the InFile, storing it in EmpArray. Return: EmpArray The array of employee data. EmpCount The number of employees just entered. In the function name return OKFlag or TooMuchDataFlag to indicate how this function ended. */ int LoadArray(fstream & InFile, EmpArrayType EmpArray, int & EmpCount) { EmployeeType Employee; int RecordSize; EmpCount = 0; RecordSize = sizeof(Employee); InFile.read(reinterpret_cast (&Employee), RecordSize); while ((! InFile.fail()) && (EmpCount < EmpMax)) { EmpArray[EmpCount] = Employee; EmpCount++; InFile.read(reinterpret_cast (&Employee), RecordSize); } if (InFile.fail()) return OKFlag; else // array ran out of room return TooMuchDataFlag; } /* Given: OutFile A binary file stream, already opened for output. EmpArray The array of employee data, from index 0 to EmpCount - 1. EmpCount The number of employee records in EmpArray. Task: To write the employee records contained in EmpArray to OutFile. Return: OutFile The modified file stream. */ void WriteToFile(fstream & OutFile, EmpArrayType EmpArray, int EmpCount) { int RecordSize, k; RecordSize = sizeof(EmployeeType); for (k = 0; k < EmpCount; k++) OutFile.write(reinterpret_cast (&EmpArray[k]), RecordSize); }