A Complete Guide to Programming in C++ part 43 doc

10 203 0
A Complete Guide to Programming in C++ part 43 doc

Đang tải... (xem toàn văn)

Thông tin tài liệu

SOLUTIONS ■ 399 default: // Invalid call to the program. cerr << usage << endl; return 2; // or: exit(2); } if( strlen(dest) == 0) // Only source file? { // yes ==> output to cout. ifstream infile(source); if( !infile ) openerror( source); ok = copy( infile, cout); // The file is closed by the ifstream destructor. } else // Copy source to destination { // file in binary mode. ifstream infile( source, ios::in | ios::binary); if( !infile ) openerror( source); else { ofstream outfile( dest, ios::out | ios::binary); if( !outfile) openerror( dest); ok = copy( infile, outfile); if( ok) cerr << "File " << source << " to file " << dest <<" copied!"<< endl; } } if(!ok) { cerr << "Error while copying!" << endl; return 3; } return 0; } bool copy( istream& is, ostream& os) // To copy { // is to os. const int BufSize = 1024; char buf[BufSize]; do { is.read( buf, BufSize); if( is.gcount() > 0) os.write(buf, is.gcount()); } while( !is.eof() && !is.fail() && !os.fail() ); if( !is.eof() ) return false; else return true; } 400 ■ CHAPTER 18 FUNDAMENTALS OF FILE INPUT AND OUTPUT Exercise 2 // // Pizza.h // Header file for Pizza_W.cpp and Pizza_R.cpp. // #include <iostream> #include <iomanip> #include <fstream> using namespace std; // Structure of a record: struct Pizza { char name[32]; float price; }; #define MAXCNT 20 // Maximum number of pizzas #define FILENAME "pizza.fle" inline void header() { cout << " * * * P I Z Z A P R O N T O * * *\n\n" << endl; } // // Pizza_w.cpp // Demonstrating blockwise writing of records. // #include "Pizza.h" Pizza pizzaMenu[MAXCNT] = { { "Pepperoni", 9.90F }, { "White Pizza", 15.90F }, { "Ham Pizza", 12.50F }, { "Calzone", 14.90F } }; int cnt = 4; char pizzaFile[256] = FILENAME; int main() // Write records. { int i; header(); cout << "\nOur standard offer:\n" << endl; cout << fixed << setprecision(2); for( i = 0; i < cnt; ++i) cout << setw(20) << pizzaMenu[i].name << setw(10) << pizzaMenu[i].price << endl; cout << "\n \n" << endl; SOLUTIONS ■ 401 // Input more pizzas via keyboard: while( cnt < MAXCNT) { cin.sync(); cin.clear(); cout << "What pizza should be added " << "to the menu?\n\n" << "Name: "; cin.getline( pizzaMenu[cnt].name, 32); if( pizzaMenu[cnt].name[0] == '\0') break; cout << "Price: "; cin >> pizzaMenu[cnt].price; if( !cin) cerr << "Invalid input!" << endl; else ++cnt; if( cnt < MAXCNT) cout << "\n and the next pizza!\n" << "Stop with <Return>.\n"; } // Add data to the file: int exitCode = 0; ofstream outFile( pizzaFile, ios::out | ios::binary); if( !outFile) { cerr << "Error opening the file!" << endl; exitCode = 1; } else { for( int i = 0; i < cnt; ++i) if( !outFile.write( (char*)&pizzaMenu[i], sizeof(Pizza)) ) { cerr << "Error writing to file!" << endl; exitCode = 2; } } if( exitCode == 0) cout << "\nData added to file " << pizzaFile << ".\n" << endl; return exitCode; } 402 ■ CHAPTER 18 FUNDAMENTALS OF FILE INPUT AND OUTPUT // // Pizza_r.cpp // Demonstrating block by block reading of records. // #include "Pizza.h" char pizzaFile[256] = FILENAME; int main() // Read and display records. { header(); ifstream inFile( pizzaFile, ios::in | ios::binary); if( !inFile) { cerr << "Pizza file does not exist!" << endl; return 1; } Pizza onePizza; int cnt = 0; cout << "\n " << "\nThe available pizzas:\n" << endl; cout << fixed << setprecision(2); while( true) if( !inFile.read( (char*)&onePizza, sizeof(Pizza)) ) break; else { cout << setw(20) << onePizza.name << setw(10) << onePizza.price << endl; ++cnt; } cout << "\n \n" << endl; if( !inFile.eof()) { cerr << "Error reading file!" << endl; return 2; } else cerr << "These are " << cnt << " pizzas!\n" << endl; return 0; } SOLUTIONS ■ 403 Exercise 3 // // Account_rw.cpp // Writes an array with objects of class Account to // a file and feed the array into another array. // #include "Account.h" // Definition of the class Account #include <iostream> #include <fstream> using namespace std; Account AccTab1[3] = { Account("Lucky, Luke", 707070, -1200.99), Account("Mickey, Mouse", 123000, 2500.0), Account("Snoopy, Dog\n" // String can contain more "Cell #: 01771234567", 543001) // than one line. }; Account AccTab2[3]; // Calls to default constructor int cnt = 3; char file[] = "account.fle"; int main() { int i = 0; // Write accounts to file ofstream outFile( file, ios::out | ios::binary ); if( ! outFile) { cerr << "Error opening file " << file << endl; return 1; } for( i = 0; i < cnt; ++i) if( !AccTab1[i].write(outFile) ) { cerr << "Error writing to file " << file << endl; return 2; } outFile.close(); 404 ■ CHAPTER 18 FUNDAMENTALS OF FILE INPUT AND OUTPUT // Reads accounts from file ifstream inFile( file, ios::out | ios::binary ); if( ! inFile) { cerr << "Error opening file " << file << endl; return 3; } for( i = 0; i < cnt; ++i) if( !AccTab2[i].read(inFile) ) { cerr << "Error reading file " << file << endl; return 4; } inFile.close(); // Displays the accounts read cout << "The file " << file << " contains the " << "following accounts:" << endl; for( i = 0; i < cnt; ++i) AccTab2[i].display(); cout << endl; return 0; } Exercise 4 // // telList.h // A class TelList to represent a list // containing names and telephone numbers. // The methods load(), save(), and saveAs() serve for // loading and saving a telephone list. // #ifndef _TelList_ #define _TelList_ #include <string> using namespace std; #define PSEUDO -1 // Pseudo position #define MAX 100 // Maximum number of elements SOLUTIONS ■ 405 // Type of a list element: struct Element { string name, telNr; }; class TelList { private: Element v[MAX]; // The array and the actual int count; // number of elements. string filename; // File name bool dirty; // true if data has been changed // but not yet saved. public: TelList() : count(0), filename(""), dirty(false) {} int getCount() { return count; } Element *retrieve( int i ) { return (i >= 0 && i < count)? &v[i] : NULL; } bool append( const Element& el ) { return append( el.name, el.telNr); } bool append( const string& name, const string& telNr); bool erase( const string& name); int search( const string& name) const; void print() const; int print( const string& name) const; int getNewEntries(); const string& getFilename() const { return filename; } bool setFilename( const string& fn) { if( fn.empty() return false; else { filename = fn; dirty = true; return true; } } bool isDirty() const { return dirty; } bool load(); bool save(); bool saveAs(); }; #endif // _TelList_ // // TelList.cpp // Implements the methods of class TelList. // #include "telList.h" // Definition of class TelList #include <iostream> #include <iomanip> #include <fstream> using namespace std; 406 ■ CHAPTER 18 FUNDAMENTALS OF FILE INPUT AND OUTPUT bool TelList::append( const string& name, const string& telNr) { if( count < MAX // Any space && name.length() > 1 // minimum 2 characters && search(name) == PSEUDO) // does not exist { v[count].name = name; v[count].telNr = telNr; ++count; dirty = true; return true; } return false; } bool TelList::erase( const string& key ) { int i = search(key); if( i != PSEUDO ) { if( i != count-1) // Copy the last element v[i] = v[count-1]; // to position i. count; dirty = true; return true; } return false; } // // Methods search(), print(), getNewEntries() // are unchanged (refer to solutions of chapter 16). // // Methods for loading and saving the telephone list. bool TelList::load() { cout << "\n Load the telephone list " << "from a file. " << "\nFile: "; string file; // Input file name. cin.sync(); cin.clear(); // No previous input getline( cin, file); if( file.empty()) { cerr << "No filename declared!" << endl; return false; } SOLUTIONS ■ 407 // Open the file for reading: ifstream infile( file.c_str(), ios::in | ios::binary); if( !infile ) { cerr << "File " << file << " could not be opened!" << endl; return false; } int i = 0; while( i < MAX) { getline( infile, v[i].name, '\0'); getline( infile, v[i].telNr, '\0'); if( !infile) break; else ++i; } if( i == MAX) cerr << "Max capacity " << MAX << " has been reached!" << endl; else if( !infile.eof()) { cerr << "Error reading file " << file << endl; return false; } count = i; filename = file; dirty = false; return true; } bool TelList::saveAs() { cout << " Save the telephone list in a file. " << "\nFile: "; string file; // Input file name. cin.sync(); cin.clear(); // No previous input getline( cin, file); if( !setFilename(file)) { cerr << "No file name declared!" << endl; return false; } else return save(); } 408 ■ CHAPTER 18 FUNDAMENTALS OF FILE INPUT AND OUTPUT bool TelList::save() // Save the telephone list. { if( filename.empty()) return saveAs(); if( !dirty) return true; ofstream outfile( filename.c_str(), ios::out | ios::binary); if( !outfile ) { cerr << "File " << filename << " could not be opened!" << endl; return false; } int i = 0; while( i < count) { outfile << v[i].name << '\0'; outfile << v[i].telNr << '\0'; if( !outfile) break; else ++i; } if( i < count) { cerr << "Error writing to file " << filename << endl; return false; } dirty = false; return true; } // // TelList_.cpp // Organize a telephone list with class TelList. // #include "telList.h" // Definition of class TelList #include <iostream> #include <string> #include <cctype> using namespace std; inline void cls() { cout << "\033[2J\n"; // If ANSI control characters are } // not available, output new-lines. . // Account_rw.cpp // Writes an array with objects of class Account to // a file and feed the array into another array. // #include "Account.h" // Definition of the class Account #include. TelList to represent a list // containing names and telephone numbers. // The methods load(), save(), and saveAs() serve for // loading and saving a telephone list. // #ifndef _TelList_ #define. FUNDAMENTALS OF FILE INPUT AND OUTPUT bool TelList::append( const string& name, const string& telNr) { if( count < MAX // Any space && name.length() > 1 // minimum 2 characters &&

Ngày đăng: 06/07/2014, 17:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan