// readrec.cpp #include #include #define MAX 100 // a simplified version of person class class Person { public: char LastName[6]; char FirstName[6]; char State[3]; Person(); }; Person::Person() { LastName[0]='\0'; FirstName[0]='\0'; State[0]='\0'; } // Read from stream a fixed length record and places in p // Fields have sizes: 5, 5 and 2 respectively int ReadRecPerson(fstream & stream, Person & p) { stream.getline(p.LastName,6); // reads 5 characters or default delimiter '\n' stream.clear(); // when delimiter not found "fail" flag is set // this clears "fail" flag if (strlen(p.LastName)==0) return 0; stream.getline(p.FirstName,6); stream.clear(); stream.getline(p.State,3); stream.clear(); return 1; } // Write to stream the Data in p int WriteRecPerson(fstream & stream, Person & p) { stream << p.LastName << p.FirstName << p.State << endl; } // Read records from "in.txt" and write in "out.txt" in reverse order // (first record last, last record first) int main() { fstream infile; fstream outfile; infile.open("in.txt",ios::in); outfile.open("out.txt",ios::out); Person people[MAX]; int i,n=0; if (infile.fail()) { // if file does not exist, abandon program cerr <<"File open failed!\n"; return 0; } while ((ReadRecPerson(infile,people[n]) != 0) && (n=0 ; i--) WriteRecPerson(outfile,people[i]); infile.close(); outfile.close(); return 1; }