660 likes | 1.07k Views
Lecture Note 10 – Templates and File Processing. Outline Templates Function Templates Class Templates File Processing Sequential-Access File Random-Access Files. Templates. Templates Function templates Specify entire range of related (overloaded) functions
E N D
Lecture Note 10 – Templates and File Processing Outline Templates Function Templates Class Templates File ProcessingSequential-Access File Random-Access Files
Templates • Templates • Function templates • Specify entire range of related (overloaded) functions • Function-template specializations • Class templates • Specify entire range of related classes • Class-template specializations
Function Templates • Overloaded functions • Similar operations • Different types of data • Function templates • Identical operations • Different types of data • Single function template • Compiler generates separate object-code functions • Type checking
Function Templates • Function-template definitions • Keyword template • List formal type parameters in angle brackets (< and >) • Each parameter preceded by keyword class or typename • class and typename interchangeable template< class T > template< typename ElementType > • Specify types of • Arguments to function • Return type of function • Variables within function
1 // Fig. 11.1: fig11_01.cpp 2 // Using template functions. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // function template printArray definition 9 template< class T > 10 void printArray( const T *array, const int count ) 11 { 12 for ( int i = 0; i < count; i++ ) 13 cout << array[ i ] << " "; 14 15 cout << endl; 16 17 } // end function printArray 18 19 int main() 20 { 21 const int aCount = 5; 22 const int bCount = 7; 23 const int cCount = 6; 24 Function template definition; declare single formal type parameter T. T is type parameter; use any valid identifier. If T is user-defined type, stream-insertion operator must be overloaded for class T. fig11_01.cpp(1 of 2)
25 int a[ aCount ] = { 1, 2, 3, 4, 5 }; 26 double b[ bCount ] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; 27 char c[ cCount ] = "HELLO"; // 6th position for null 28 29 cout << "Array a contains:" << endl; 30 31 // call integer function-template specialization 32 printArray( a, aCount ); 33 34 cout << "Array b contains:" << endl; 35 36 // call double function-template specialization 37 printArray( b, bCount ); 38 39 cout << "Array c contains:" << endl; 40 41 // call character function-template specialization 42 printArray( c, cCount ); 43 44 return0; 45 46 } // end main fig11_01.cpp(2 of 2) Creates complete function-template specialization for printing array of ints: void printArray( const int *array, const int count ){for ( int i = 0; i < count; i++ ) cout << array[ i ] << " " cout << endl; } // end function printArray Compiler infers T is double; instantiates function-template specialization where T is double. Array a contains: 1 2 3 4 5 Array b contains: 1.1 2.2 3.3 4.4 5.5 6.6 7.7 Array c contains: H E L L O fig11_01.cppoutput (1 of 1) Compiler infers T is char; instantiates function-template specialization where T is char.
#include <iostream.h> //Tplate2.cpp #define max 5 template <class Tpt> Tpt SumArray(const Tpt a[], int ) { int i; Tpt sum; sum = a[0]; for( i=1; i < max; i++) sum = sum + a[i]; return sum; } int main(void) { char screenoff; int a[max] = {1,2,3,4,5}; float b[max]= {1.1, 2.2, 3.3, 4.4, 5.5}; cout << "Number sum : " << SumArray(a, max) << endl; cout << "Number sum : " << SumArray(b, max) << endl; cin >> screenoff; }
Class Templates • Stack • LIFO (last-in-first-out) structure • Class templates • Generic programming • Describe notion of stack generically • Instantiate type-specific version • Parameterized types • Require one or more type parameters • Customize “generic class” template to form class-template specialization
1 // Fig. 11.2: tstack1.h 2 // Stack class template. 3 #ifndefTSTACK1_H 4 #defineTSTACK1_H 5 6 template< class T > 7 class Stack { 8 9 public: 10 Stack( int = 10 ); // default constructor (stack size 10) 11 12 // destructor 13 ~Stack() 14 { 15 delete [] stackPtr; 16 17 } // end ~Stack destructor 18 19 bool push( const T& ); // push an element onto the stack 20 bool pop( T& ); // pop an element off the stack 21 22 // determine whether Stack is empty 23 bool isEmpty() const 24 { 25 return top == -1; 26 27 } // end function isEmpty 28 Specify class-template definition; type parameter T indicates type of Stack class to be created. Function parameters of type T. tstack1.h (1 of 3)
29 // determine whether Stack is full 30 bool isFull() const 31 { 32 return top == size - 1; 33 34 } // end function isFull 35 36 private: 37 int size; // # of elements in the stack 38 int top; // location of the top element 39 T *stackPtr; // pointer to the stack 40 41 }; // end class Stack 42 43 // constructor 44 template< class T > 45 Stack< T >::Stack( int s ) 46 { 47 size = s > 0 ? s : 10; 48 top = -1; // Stack initially empty 49 stackPtr = new T[ size ]; // allocate memory for elements 50 51 } // end Stack constructor 52 53 // push element onto stack; 54 // if successful, return true; otherwise, return false Array of elements of type T. tstack1.h (2 of 3) Member functions preceded with header template< class T > Use binary scope resolution operator (::) with class-template name (Stack< T >) to tie definition to class template’s scope. Constructor creates array of type T. For example, compiler generates stackPtr = new T[ size ]; for class-template specialization Stack< double >.
55 template< class T > 56 bool Stack< T >::push( const T &pushValue ) 57 { 58 if ( !isFull() ) { 59 stackPtr[ ++top ] = pushValue; // place item on Stack 60 returntrue; // push successful 61 62 } // end if 63 64 returnfalse; // push unsuccessful 65 66 } // end function push 67 68 // pop element off stack; 69 // if successful, return true; otherwise, return false 70 template< class T > 71 bool Stack< T >::pop( T &popValue ) 72 { 73 if ( !isEmpty() ) { 74 popValue = stackPtr[ top-- ]; // remove item from Stack 75 returntrue; // pop successful 76 77 } // end if 78 79 return false; // pop unsuccessful 80 81 } // end function pop 82 83 #endif Member functions preceded with header template< class T > tstack1.h (3 of 3) Use binary scope resolution operator (::) with class-template name (Stack< T >) to tie definition to class template’s scope.
1 // Fig. 11.3: fig11_03.cpp 2 // Stack-class-template test program. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 #include"tstack1.h" // Stack class template definition 10 11 int main() 12 { 13 Stack< double > doubleStack( 5 ); 14 double doubleValue = 1.1; 15 16 cout << "Pushing elements onto doubleStack\n"; 17 18 while ( doubleStack.push( doubleValue ) ) { 19 cout << doubleValue << ' '; 20 doubleValue += 1.1; 21 22 } // end while 23 24 cout << "\nStack is full. Cannot push " << doubleValue 25 << "\n\nPopping elements from doubleStack\n"; Link to class template definition. fig11_03.cpp(1 of 2) Instantiate object of class Stack< double >. Invoke function push of class-template specialization Stack< double >.
26 27 while ( doubleStack.pop( doubleValue ) ) 28 cout << doubleValue << ' '; 29 30 cout << "\nStack is empty. Cannot pop\n"; 31 32 Stack< int > intStack; 33 int intValue = 1; 34 cout << "\nPushing elements onto intStack\n"; 35 36 while ( intStack.push( intValue ) ) { 37 cout << intValue << ' '; 38 ++intValue; 39 40 } // end while 41 42 cout << "\nStack is full. Cannot push " << intValue 43 << "\n\nPopping elements from intStack\n"; 44 45 while ( intStack.pop( intValue ) ) 46 cout << intValue << ' '; 47 48 cout << "\nStack is empty. Cannot pop\n"; 49 50 return0; 51 52 } // end main Invoke function pop of class-template specialization Stack< double >. fig11_03.cpp(2 of 2) Note similarity of code for Stack< int > to code for Stack< double >. Pushing elements onto doubleStack 1.1 2.2 3.3 4.4 5.5 Stack is full. Cannot push 6.6 Popping elements from doubleStack 5.5 4.4 3.3 2.2 1.1 Stack is empty. Cannot pop Pushing elements onto intStack 1 2 3 4 5 6 7 8 9 10 Stack is full. Cannot push 11 Popping elements from intStack 10 9 8 7 6 5 4 3 2 1 Stack is empty. Cannot pop
Class Templates and Nontype Parameters • Class templates • Nontype parameters • Default arguments • Treated as consts • Example: template< class T, int elements > Stack< double, 100 > mostRecentSalesFigures; • Declares object of type Stack< double, 100>
File Processing • Storage of data • Arrays, variables are temporary • Files are permanent • Magnetic disk, optical disk, tapes • File processing • Create, update, process files • Sequential and random access
The Data Hierarchy • From smallest to largest • Bit (binary digit) • 1 or 0 • Everything in computer ultimately represented as bits • Cumbersome for humans to use • Character set • Digits, letters, symbols used to represent data • Every character represented by 1's and 0's • Byte: 8 bits • Can store a character (char) • Also Unicode for large character sets (wchar_t)
The Data Hierarchy • From smallest to largest (continued) • Field: group of characters with some meaning • Your name • Record: group of related fields • struct or class in C++ • In payroll system, could be name, SS#, address, wage • Each field associated with same employee • Record key: field used to uniquely identify record • File: group of related records • Payroll for entire company • Sequential file: records stored by key • Database: group of related files • Payroll, accounts-receivable, inventory…
Sally Black Tom Blue Judy Green File Iris Orange Randy Red Judy Green Record Judy Field 01001010 Byte (ASCII character J) 1 Bit The Data Hierarchy
... n-1 7 9 6 2 4 8 1 5 0 3 end-of-file marker ... Files and Streams • C++ views file as sequence of bytes • Ends with end-of-file marker • When file opened • Object created, stream associated with it • cin, cout, etc. created when <iostream> included • Communication between program and file/device
Files and Streams • To perform file processing • Include <iostream> and <fstream> • Class templates • basic_ifstream (input) • basic_ofstream (output) • basic_fstream (I/O) • typedefs for specializations that allow char I/O • ifstream (char input) • ofstream (char output) • fstream (char I/O)
basic_ios basic_istream basic_ostream basic_ofstream basic_iostream basic_ifstream basic_fstream Files and Streams • Opening files • Create objects from template • Derive from stream classes • Can use stream methods from Ch. 12 • put, get, peek, etc.
Creating a Sequential-Access File • C++ imposes no structure on file • Concept of "record" must be implemented by programmer • To open file, create objects • Creates "line of communication" from object to file • Classes • ifstream (input only) • ofstream (output only) • fstream (I/O) • Constructors take file name and file-open mode ofstream outClientFile( "filename", fileOpenMode ); • To attach a file later Ofstream outClientFile; outClientFile.open( "filename", fileOpenMode);
Creating a Sequential-Access File • File-open modes • ofstream opened for output by default • ofstream outClientFile( "clients.dat", ios::out ); • ofstream outClientFile( "clients.dat");
Creating a Sequential-Access File • Operations • Overloaded operator! • !outClientFile • Returns nonzero (true) if badbit or failbit set • Opened non-existent file for reading, wrong permissions • Overloaded operator void* • Converts stream object to pointer • 0 when when failbit or badbit set, otherwise nonzero • failbit set when EOF found • while ( cin >> myVariable ) • Implicitly converts cin to pointer • Loops until EOF
Creating a Sequential-Access File • Operations • Writing to file (just like cout) • outClientFile << myVariable • Closing file • outClientFile.close() • Automatically closed when destructor called
[file example.txt] Writing this to a file // basic file operations #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; }
[file example.txt] This is a line. This is another line. // writing on a text file #include <iostream> #include <fstream> using namespace std; int main () { // ofstream myfile ("example.txt"); ofstream myfile; myfile.open ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; }
1 // Fig. 14.4: fig14_04.cpp 2 // Create a sequential file. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::ios; 8 using std::cerr; 9 using std::endl; 10 11 #include <fstream> 12 13 using std::ofstream; 14 15 #include <cstdlib> // exit prototype 16 17 int main() 18 { 19 // ofstream constructor opens file 20 ofstream outClientFile( "clients.dat", ios::out ); 21 22 // exit program if unable to create file 23 if ( !outClientFile ) { // overloaded ! operator 24 cerr << "File could not be opened" << endl; 25 exit( 1 ); 26 27 } // end if Notice the the header files required for file I/O. ofstream object created and used to open file "clients.dat". If the file does not exist, it is created. ! operator used to test if the file opened properly. fig14_04.cpp(1 of 2)
28 29 cout << "Enter the account, name, and balance." << endl 30 << "Enter end-of-file to end input.\n? "; 31 32 int account; 33 char name[ 30 ]; 34 double balance; 35 36 // read account, name and balance from cin, then place in file 37 while ( cin >> account >> name >> balance ) { 38 outClientFile << account << ' ' << name << ' ' << balance 39 << endl; 40 cout << "? "; 41 42 } // end while 43 44 return0; // ofstream destructor closes file 45 46 } // end main Write data to file like a regular stream. cin is implicitly converted to a pointer. When EOF is encountered, it returns 0 and the loop stops. fig14_04.cpp(2 of 2) File closed when destructor called for object. Can be explicitly closed with close(). Enter the account, name, and balance. Enter end-of-file to end input. ? 100 Jones 24.98 ? 200 Doe 345.67 ? 300 White 0.00 ? 400 Stone -42.16 ? 500 Rich 224.62 ? ^Z fig14_04.cppoutput (1 of 1)
Reading Data from a Sequential-Access File • Reading files • ifstream inClientFile( "filename", ios::in ); • Overloaded ! • !inClientFile tests if file was opened properly • operator void* converts to pointer • while (inClientFile >> myVariable) • Stops when EOF found (gets value 0)
1 // Fig. 14.7: fig14_07.cpp 2 // Reading and printing a sequential file. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::ios; 8 using std::cerr; 9 using std::endl; 10 using std::left; 11 using std::right; 12 using std::fixed; 13 using std::showpoint; 14 15 #include <fstream> 16 17 using std::ifstream; 18 19 #include <iomanip> 20 21 using std::setw; 22 using std::setprecision; 23 24 #include <cstdlib> // exit prototype 25 26 void outputLine( int, const char * const, double ); 27 fig14_07.cpp(1 of 3)
28 int main() 29 { 30 // ifstream constructor opens the file 31 ifstream inClientFile( "clients.dat", ios::in ); 32 33 // exit program if ifstream could not open file 34 if ( !inClientFile ) { 35 cerr << "File could not be opened" << endl; 36 exit( 1 ); 37 38 } // end if 39 40 int account; 41 char name[ 30 ]; 42 double balance; 43 44 cout << left << setw( 10 ) << "Account" << setw( 13 ) 45 << "Name" << "Balance" << endl << fixed << showpoint; 46 47 // display each record in file 48 while ( inClientFile >> account >> name >> balance ) 49 outputLine( account, name, balance ); 50 51 return0; // ifstream destructor closes the file 52 53 } // end main Open and test file for input. Read from file until EOF found. fig14_07.cpp(2 of 3)
54 55 // display single record from file 56 void outputLine( int account, const char * const name, 57 double balance ) 58 { 59 cout << left << setw( 10 ) << account << setw( 13 ) << name 60 << setw( 7 ) << setprecision( 2 ) << right << balance 61 << endl; 62 63 } // end function outputLine fig14_07.cpp(3 of 3)fig14_07.cppoutput (1 of 1) Account Name Balance 100 Jones 24.98 200 Doe 345.67 300 White 0.00 400 Stone -42.16 500 Rich 224.62
Data gets overwritten 300 Worthington 0.00 Updating Sequential-Access Files • Updating sequential files • Risk overwriting other data • Example: change name "White" to "Worthington" • Old data 300 White 0.00 400 Jones 32.87 • Insert new data • Formatted text different from internal representation • Problem can be avoided, but awkward 300 White 0.00 400 Jones 32.87 300 Worthington 0.00ones 32.87
Reading Data from a Sequential-Access File • File position pointers • Number of next byte to read/write • Functions to reposition pointer • seekg (seek get for istream class) • seekp (seek put for ostream class) • seekg and seekp take offset and direction • Offset: number of bytes relative to direction • Direction (ios::beg default) • ios::beg - relative to beginning of stream • ios::cur - relative to current position • ios::end - relative to end
Reading Data from a Sequential-Access File • Examples • fileObject.seekg(0) • Goes to front of file (location 0) because ios::beg is default • fileObject.seekg(n) • Goes to nth byte from beginning • fileObject.seekg(n, ios::cur) • Goes n bytes forward • fileObject.seekg(y, ios::end) • Goes y bytes back from end • fileObject.seekg(0, ios::cur) • Goes to last byte • seekp similar
Reading Data from a Sequential-Access File • To find pointer location • tellg and tellp • location = fileObject.tellg() • Upcoming example
#include "stdafx.h" // obtaining file size #include <iostream> #include <fstream> using namespace std; int main () { long begin,end; ifstream myfile ("example.txt"); begin = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size is: " << (end-begin) << " bytes.\n"; return 0; } [file example.txt] This is a line. This is another line. Slide 27 output size is: 40 bytes.
#include <fstream.h> //Direct1.cpp #include <iostream.h> int main () { char c, letters[7] = {'a','b','c','d','e','f','g'}; fstream fp; // pointer to file fp.open("datafile.dat", ios::out | ios::in); if (!fp.good()) { cout << "ERROR: cannot create file "; return 1; } cout << "Open data file\n"; for (int i = 0; i <= 6; i++) { fp.seekg(i * sizeof(char), ios::beg); //pointer location fp << letters[i]; // write here cout << "Write " << letters[i] << " at position " << i << endl; } fp.seekg(6 * sizeof(char), ios::beg); fp >> c; cout << "\nRead " << c << " at position 6\n"; [file datafile.dat] abcdefg fp.seekg(0 * sizeof(char), ios::beg); fp >> c; cout << "Read " << c << " at position 0\n"; fp.close(); return 0; }
Random-Access Files • Instant access • Want to locate record quickly • Airline reservations, ATMs • Sequential files must search through each one • Random-access files are solution • Instant access • Insert record without destroying other data • Update/delete items without changing other data
Random-Access Files • C++ imposes no structure on files • Programmer must create random-access files • Simplest way: fixed-length records • Calculate position in file from record size and key
Creating a Random-Access File • "1234567" (char *) vs 1234567 (int) • char * takes 8 bytes (1 for each character + null) • int takes fixed number of bytes (perhaps 4) • 123 same size in bytes as 1234567 • << operator and write() • outFile << number • Outputs number (int) as a char * • Variable number of bytes • outFile.write( const char *, size ); • Outputs raw bytes • Takes pointer to memory location, number of bytes to write • Copies data directly from memory into file • Does not convert to char *
Creating a Random-Access File • Example outFile.write( reinterpret_cast<const char *>(&number), sizeof( number ) ); • &number is an int * • Convert to const char * with reinterpret_cast • sizeof(number) • Size of number (an int) in bytes • read function similar (more later) • Must use write/read between compatible machines • Only when using raw, unformatted data • Use ios::binary for raw writes/reads
Creating a Random-Access File • Usually write entire struct or object to file Example: Example consists of a file creation datafile.dat and a random reading of file records that were created from the structure Example does not provide all facilities to read, write, update and delete records it does provide enough information to develop such a system Record access is by number although easily modifiable to relate say part number to record etc
#include <fstream.h> //Direct2.cpp #include <iostream.h> int main () { char screenoff; struct Scar_parts { int part_no; char name[20]; int number_of; }; Scar_parts Rover_parts; fstream fp; // pointer to file ofstream cars("datafile.dat", ios::out | ios::in | ios::binary); if (!cars) { cout << "ERROR: cannot create file "; return 1; }
cout << "Open data file\n"; cout << "Input part number, Part name, Number sent\n"; Rover_parts.part_no = 0; while(Rover_parts.part_no < 5) { cin >> Rover_parts.part_no >> Rover_parts.name >> Rover_parts.number_of; fp.seekg(Rover_parts.part_no * sizeof(Scar_parts)); cars.write(reinterpret_cast<const char*> (&Rover_parts), sizeof(Scar_parts)); } cars.close(); fp.open("datafile.dat", ios::in | ios::binary | ios::beg); cout << "Output part number, Part name, Number sent\n"; fp.seekg(0 * sizeof(Scar_parts), ios::beg); fp.read((char*) &Rover_parts, sizeof(Scar_parts)); cout << Rover_parts.number_of << Rover_parts.name << Rover_parts.part_no ; cout << "\nSecond record\n"; fp.seekg(2 * sizeof(Scar_parts), ios::beg); fp.read((char*) &Rover_parts, sizeof(Scar_parts)); cout << Rover_parts.number_of << Rover_parts.name << Rover_parts.part_no ; cin >> screenoff; }
Lecture Note 10 – Templates and File Processing Summary Templates Function Templates Class Templates File ProcessingSequential-Access File Random-Access Files
Example_Creating a Random-Access File Problem statement • Credit processing program • Store at most 100 fixed-length records • Record • Account number (key) • First and last name • Balance • Account operations • Update, create new, delete, list all accounts in a file • Next: program to create blank 100-record file
1 // Fig. 14.10: clientData.h 2 // Class ClientData definition used in Fig. 14.12–Fig. 14.15. 3 #ifndefCLIENTDATA_H 4 #defineCLIENTDATA_H 5 6 #include <iostream> 7 8 using std::string; 9 10 class ClientData { 11 12 public: 13 14 // default ClientData constructor 15 ClientData( int = 0, string = "", string = "", double = 0.0 ); 16 17 // accessor functions for accountNumber 18 void setAccountNumber( int ); 19 int getAccountNumber() const; 20 21 // accessor functions for lastName 22 void setLastName( string ); 23 string getLastName() const; 24 Class ClientData stores the information for each person. 100 blank ClientData objects will be written to a file. clientData.h(1 of 2)
25 // accessor functions for firstName 26 void setFirstName( string ); 27 string getFirstName() const; 28 29 // accessor functions for balance 30 void setBalance( double ); 31 double getBalance() const; 32 33 private: 34 int accountNumber; 35 char lastName[ 15 ]; 36 char firstName[ 10 ]; 37 double balance; 38 39 }; // end class ClientData 40 41 #endif Put limits on the size of the first and last name. accountNumber (an int) and balance (double) are already of a fixed size. clientData.h(2 of 2)