精華區beta NTUBA92 關於我們 聯絡資訊
#include <fstream.h> #include <iomanip.h> #include <stdlib.h> const int MAXCHARS = 21; char old_master[MAXCHARS] = "oldbook.mas"; // here are the files we will be char new_master[MAXCHARS] = "newbook.mas"; // working with char transactions[MAXCHARS] = "book.trn"; void do_update(void); int main() { do_update(); return 0; } // update function // precondition: both a master file named oldbook.mas and // : a transaction file named book.trn exist on // : the current directory // : and both files are in date order // postcondition: a new master file named newbook.mas is created void do_update(void) { const int MAXDATE = 8; int idmast, idtrans, balance, sold, returned, bought; int ch; char date[MAXDATE]; ifstream oldmast, trans; ofstream newmast; // open and check the old_master file oldmast.open(old_master); if (oldmast.fail()) { cout << "\nThe input file " << old_master << "was not successfully opened" << "\n Please check that the file currently exists." << endl; exit(1); } // open and check the new_master file newmast.open(new_master); if (newmast.fail()) { cout << "\nFailed to open the new master file " << new_master << " for output." << endl; exit(1); } // open and check the transaction file trans.open(transactions); if (trans.fail()) { cout << "\nThe input file " << trans << " was not successfully opened" << "\n Please check that the file currently exits." << endl; exit(1); } // read the first old master file record oldmast >> idmast >> balance; while( (ch = trans.peek()) != EOF) { // read one transactions record trans >> idtrans >> date >> sold >> returned >> bought; // if no match keep writing and reading the master file while (idtrans > idmast) { newmast << '\n' << idmast << setw(6) << balance; oldmast >> idmast >> balance; } balance = balance + bought - sold + returned; } // write the last updated new master file newmast << '\n' << idmast << setw(6) << balance; // write any remaining old master records to the new master while ( (ch = oldmast.peek()) != EOF) { oldmast >> idmast >> balance; newmast << '\n' << idmast << setw(6) << balance; } oldmast.close(); newmast.close(); trans.close(); cout << "\n....File update complete...\n"; return; } -- ※ 發信站: 批踢踢實業坊(ptt.twbbs.org) ◆ From: ntumcc66.mba.ntu.edu.tw