Chapter 14 File Processing

Size: px
Start display at page:

Download "Chapter 14 File Processing"

Transcription

1 Chapter 14 File Processing Outline 14.1 Introd uction 14.2 The Data Hie rarchy 14.3 File s and Stre am s 14.4 Cre ating a Se q ue ntialacce ss File 14.5 Re ad ing Data from a Se q ue ntialacce ss File 14.6 Upd ating Se q ue ntialacce ss File s 14.7 Rand om Acce ss File s 14.8 Cre ating a Rand om Acce ss File 14.9 Writing Data Rand om ly to a Rand om Acce ss File Re ad ing Data Se que ntially from a Rand om Acce ss File Exam ple : A Transaction Proce ssing Prog ram Input/ Output of O bje cts

2 14.1 Introd uction Data files can be created, updated, and processed by C++ programs Files are used for permanent storage of large amounts of data Storage of data in variables and arrays is only temporary

3 14.2 The Data Hie rarchy Bit - smallest data item value of 0 or 1 Byte 8 bits used to store a character Decimal digits, letters, and special symbols Field - group of characters conveying meaning Example: your name Record group of related fields Represented a struct or a class Example: In a payroll system, a record for a particular employee that contained his/her identification number, name, address, etc. File group of related records Example: payroll file Database group of related files

4 14.2 The Data Hie rarchy (II) Sally Black Tom Blue Judy Green Iris Orange Randy Red File Judy Green Record Judy Field Byte(ASCII character J) 1 Bit Record key identifies a record to facilitate the retrieval of specific records from a file Sequential file records typically sorted by key

5 14.3 File s and Stre am s C++ views each file as a sequence of bytes File ends with the end-of-file marker Stream created when a file is opened File processing Headers <iostream.h> and <fstream.h> class ifstream - input class ofstream - output class fstream - either input or output

6 14.4 Cre ating a Se q ue ntialacce ss File Files are opened by creating objects of stream classes ifstream, ofstream or fstream File stream member functions for object file: file.open( Filename, fileopenmode); file.close(); destructor automatically closes file if not explicitly closed File open modes: Mode Description Makes a "line of communication" with the object and the file. ios::app ios::ate ios::in ios::out ios::trunc ios::binary Write all output to the end of the file. Open a file for output and move to the end of the file (normally used to append data to a file). Data can be written anywhere in the file. Open a file for input. Open a file for output. Discard the file s contents if it exists (this is also the default action for ios::out) Open a file for binary (i.e., non-text) input or output.

7 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; 1. Load he ad e rs 1.1 Initialize ofstream obje ct 8 using std::cerr; 9 using std::endl; #include <fstream> using std::ofstream; #include <cstdlib> int main() ofstream objects open a file for output (i.e., write to the file). If the file "clients.dat" does not exist, it is created. ios::out is the default for ofstream objects. 18 { 19 // ofstream constructor opens file Deitel ofstream & Associates, outclientfile( Inc. All rights "clients.dat", reserved. ios::out );

8 21 22 if (!outclientfile ) { // overloaded! operator 23 cerr << "File could not be opened" << endl; 24 exit( 1 ); // prototype in cstdlib 25 } cout << "Enter the account, name, and balance.\n" 28 << "Enter end-of-file to end input.\n? "; int account; 31 char name[ 30 ]; 32 double balance; while ( cin >> account >> name >> balance ) { 35 outclientfile << account << ' ' << name 36 << ' ' << balance << '\n'; 37 cout << "? "; 38 } return 0; // ofstream destructor closes file 41 } Enter the account, name, and balance. Enter EOF to end input.? 100 Jones 24.98? 200 Doe ? 300 White 0.00? 400 Stone ? 500 Rich ? ^Z Overloaded operator! returns true if failbit or badbit are set. 2. Te st for file ope n 2.1 Input value s 3. O utput to file Input sets of data. When end-of-file or bad data is input, cin returns 0 (normally it returns cin), and the while loop ends. Rather than outputting to cout, we output to outclientfile, which is linked to clients.dat Prog ram Output outclientfile's destructor automatically closes client.dat

9 14.5 Re ad ing Data from a Se que ntial Acce ss File File stream member functions for repositioning file position pointer: seekg (seek get) for istream and seekp (seek put) for ostream // position to the nth byte of fileobject // assumes ios::beg fileobject.seekg( n ); // position n bytes forward in fileobject fileobject.seekg( n, ios::cur ); // position y bytes back from end of fileobject fileobject.seekg( y, ios::end ); // position at end of fileobject fileobject.seekg( 0, ios::end ); tellg and tellp return current location of pointer location = fileobject.tellg() //returns long

10 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; #include <fstream> using std::ifstream; #include <iomanip> using std::setiosflags; 18 using std::resetiosflags; 19 using std::setw; 20 using std::setprecision; #include <cstdlib> void outputline( int, const char * const, double ); int main() 27 { Deitel // ifstream & Associates, constructor Inc. All rights opens reserved. the file Re ad ing a se que ntial file 1. Load he ade r 1.1 Function prototype

11 29 ifstream inclientfile( "clients.dat", ios::in ); if (!inclientfile ) { 32 cerr << "File could not be opened\n"; 33 exit( 1 ); 34 } int account; 37 char name[ 30 ]; 38 double balance; cout << setiosflags( ios::left ) << setw( 10 ) << "Account" 41 << setw( 13 ) << "Name" << "Balance\n" 42 << setiosflags( ios::fixed ios::showpoint ); while ( inclientfile >> account >> name >> balance ) 45 outputline( account, name, balance ); return 0; // ifstream destructor closes the file 48 } void outputline( int acct, const char * const name, double bal ) 51 { 52 cout << setiosflags( ios::left ) << setw( 10 ) << acct 53 << setw( 13 ) << name << setw( 7 ) << setprecision( 2 ) 54 << resetiosflags( ios::left ) 55 << bal << '\n'; } Deitel & Associates, Inc. All rights reserved. Opens "clients.dat" for input (i.e., read from file) 1.2 Initialize ifstream obje ct Account Name 1.3 Te st for ope n 1.4 Initialize variab le s Balance 2. Form at table Reads data, record by record, and puts it into account, 3. Output name d ata and balance. 3.1 Function d e finition Calls outputline, which formats data and outputs it to the screen. while loop continues until the end of the file stream, when 0 is returned (instead of inclientfile). The destructor automatically closes clients.dat

12 Account Name Balance 100 Jones Doe White Stone Rich Prog ram Output

13 1 // Fig. 14.8: fig14_08.cpp 2 // Credit inquiry program 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::ios; 8 using std::cerr; 9 using std::endl; #include <fstream> using std::ifstream; #include <iomanip> using std::setiosflags; 18 using std::resetiosflags; 19 using std::setw; 20 using std::setprecision; #include <cstdlib> enum RequestType { ZERO_BALANCE = 1, CREDIT_BALANCE, 25 DEBIT_BALANCE, END }; 26 int getrequest(); 27 bool shoulddisplay( int, double ); 28 void outputline( int, const char * const, double ); int main() 31 { Deitel // ifstream & Associates, constructor Inc. All rights opens reserved. the file Cre d it inq uiry prog ram 1. Load he ad e rs 1.1 Function prototype s 1.2 e num e ration

14 33 ifstream inclientfile( "clients.dat", ios::in ); if (!inclientfile ) { 36 cerr << "File could not be opened" << endl; 37 exit( 1 ); 38 } int request, account; 41 char name[ 30 ]; 42 double balance; cout << "Enter request\n" 45 << " 1 - List accounts with zero balances\n" 46 << " 2 - List accounts with credit balances\n" 47 << " 3 - List accounts with debit balances\n" 48 << " 4 - End of run" 49 << setiosflags( ios::fixed ios::showpoint ); 50 request = getrequest(); while ( request!= END ) { switch ( request ) { 55 case ZERO_BALANCE: 56 cout << "\naccounts with zero balances:\n"; 57 break; 58 case CREDIT_BALANCE: 59 cout << "\naccounts with credit balances:\n"; 60 break; 61 case DEBIT_BALANCE: 62 cout << "\naccounts with debit balances:\n"; 63 break; Deitel } & Associates, Inc. All rights reserved. 1.1 O pe n file for input 1.2 Te st for e rrors 1.3 Initialize variab le s 2. Prom pt use r 2.1 G e t input 2.2 switch state m e nt

15 65 66 inclientfile >> account >> name >> balance; while (!inclientfile.eof() ) { 69 if ( shoulddisplay( request, balance ) ) 70 outputline( account, name, balance ); inclientfile >> account >> name >> balance; 73 } inclientfile.clear(); // reset eof for next input 76 inclientfile.seekg( 0 ); // move to beginning of file read data from file, copy into account, name and balance 77 request = getrequest(); 78 } cout << "End of run." << endl; return 0; // ifstream destructor closes the file 83 } int getrequest() 86 { 87 int request; do { 90 cout << "\n? "; 91 cin >> request; 92 } while( request < ZERO_BALANCE && request > END ); return request; 95 } bool Deitel shoulddisplay( & Associates, Inc. int All rights type, reserved. double balance ) Put file position pointer back to beginning. 2.3 Input d ata from file 2.4 De cid e whe the r to d isplay d ata 2.5 Re se t eof for ne xt input 2.6 Move to be g inning o f file 2.7 Loop untilend e nte re d 3. Function d e finitions

16 98 { 99 if ( type == CREDIT_BALANCE && balance < 0 ) 100 return true; if ( type == DEBIT_BALANCE && balance > 0 ) 103 return true; if ( type == ZERO_BALANCE && balance == 0 ) 106 return true; return false; 109} void outputline( int acct, const char * const name, double bal ) 112{ 113 cout << setiosflags( ios::left ) << setw( 10 ) << acct 114 << setw( 13 ) << name << setw( 7 ) << setprecision( 2 ) 115 << resetiosflags( ios::left ) 116 << bal << '\n'; 117} 3. Function d e finitions

17 Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run? 1 Accounts with zero balances: 300 White 0.00? 2 Prog ram Output Accounts with credit balances: 400 Stone ? 3 Accounts with debit balances: 100 Jones Doe Rich ? 4 End of run.

18 14.6 Upd ating Se q ue ntialacce ss File s Sequential access file Cannot be modified without the risk of destroying other data 300 White Jones (old data in file) if we want to change White's name to Worthington, 300 Worthington White Jones Worthington 0.00ones Data gets overwritten Formatted text which is output to a file is very different than the internal representation

19 Random access files 14.7 Rand om Acce ss File s access individual records without searching through other records Instant access to records in a file Data can be inserted without destroying other data Data previously stored can be updated or deleted without overwriting. Implemented using fixed length records } byte offsets } 100 bytes } 100 bytes } 100 bytes } 100 bytes } 100 bytes } 100 bytes

20 14.8 Cre ating a Rand om Acce ss File write - outputs a fixed number of bytes beginning at a specific location in memory to the specified stream When writing an integer number to a file, outfile.write( reinterpret_cast<const char *>( &number ), sizeof( number ) ); First argument: pointer of type const char * (location to write from) address of number cast into a pointer Second argument: number of bytes to write(sizeof(number)) recall that data is represented internally in binary (thus, integers can be stored in 4 bytes) Do not use outfile << number; could print 1 to 11 digits, each digit taking up a byte of storage

21 1 // Fig : clntdata.h 2 // Definition of struct clientdata used in 3 // Figs , 14.12, and #ifndef CLNTDATA_H 5 #define CLNTDATA_H 6 7 struct clientdata { 8 int accountnumber; 9 char lastname[ 15 ]; 10 char firstname[ 10 ]; 11 double balance; 12 }; #endif 15 // Fig : fig14_11.cpp 16 // Creating a randomly accessed file sequentially 17 #include <iostream> using std::cerr; 20 using std::endl; 21 using std::ios; #include <fstream> using std::ofstream; #include <cstdlib> #include "clntdata.h" int main() 32 { 33 ofstream outcredit( "credit.dat", ios::binary ); De fine struct 1.1 Load he ad e rs 1.2 Initialize ofstream obje ct

22 35 if (!outcredit ) { 36 cerr << "File could not be opened." << endl; 37 exit( 1 ); 38 } clientdata blankclient = { 0, "", "", 0.0 }; for ( int i = 0; i < 100; i++ ) 43 outcredit.write( 44 reinterpret_cast<const char *>( &blankclient ), 45 sizeof( clientdata ) ); 1.3 Che ck for file ope n 1.4 Initialize struct variab le 2. Loop and write d ata to file 46 return 0; 47 } Creates a random access file by writing equallysized groups of data to the file. Each group is of size sizeof(clientdata)

23 14.9 Writing Data Rand om ly to a Rand om Acce ss File seekp can be used in combination with write to store data at exact locations in an output file

24 1 // Fig : fig14_12.cpp 2 // Writing to a random access file 3 #include <iostream> 4 5 using std::cerr; 6 using std::endl; 7 using std::cout; 8 using std::cin; 9 using std::ios; #include <fstream> using std::ofstream; #include <cstdlib> 16 #include "clntdata.h" int main() 19 { 20 ofstream outcredit( "credit.dat", ios::binary ); if (!outcredit ) { 23 cerr << "File could not be opened." << endl; 24 exit( 1 ); Deitel } & Associates, Inc. All rights reserved. 1. Load he ade r 1.1 Initialize ofstream obje ct 1.2 Che ck for file ope n

25 26 27 cout << "Enter account number " 28 << "(1 to 100, 0 to end input)\n? "; clientdata client; 31 cin >> client.accountnumber; while ( client.accountnumber > 0 && 34 client.accountnumber <= 100 ) { 35 cout << "Enter lastname, firstname, balance\n? "; 36 cin >> client.lastname >> client.firstname 37 >> client.balance; outcredit.seekp( ( client.accountnumber - 1 ) * 40 sizeof( clientdata ) ); 41 outcredit.write( 42 reinterpret_cast<const char *>( &client ), 43 sizeof( clientdata ) ); cout << "Enter account number\n? "; 46 cin >> client.accountnumber; 47 } return 0; } Deitel & Associates, Inc. All rights reserved. Enter account number (1 to 100, 0 to end input) Enter lastname, firstname, balance? Barker Doug Input d ata 2.1 Se t pointe r to appropriate place in file 2.2 W rite to file 2.3 Loop untile nd Find the appropriate position in the file. The groups are of size sizeof(clientdata), and the first position is at location 0. Accounts sorted by accountnumber

26 Enter account number (1 to 100, 0 to end input)? 37 Enter lastname, firstname, balance? Barker Doug 0.00 Enter account number? 29 Enter lastname, firstname, balance? Brown Nancy Enter account number? 96 Enter lastname, firstname, balance? Stone Sam Enter account number? 88 Enter lastname, firstname, balance? Smith Dave Enter account number? 33 Enter lastname, firstname, balance? Dunn Stacey Enter account number? 0 Prog ram Output

27 14.10 Re ad ing Data Se que ntially from a Rand om Acce ss File read - inputs a fixed number of bytes from the specified stream to an area in memory beginning at a specified address similar to write infile.read( reinterpret_cast<char *>( &number ), sizeof( int ) ); First argument: pointer of type char * (location to put bytes) Second argument: number of bytes to read: sizeof( int ) Do not use infile >> number; fast sorting with direct access techniques

28 1 // Fig : fig14_14.cpp 2 // Reading a random access file sequentially 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 using std::ios; 8 using std::cerr; 9 10 #include <iomanip> using std::setprecision; 13 using std::setiosflags; 14 using std::resetiosflags; 15 using std::setw; #include <fstream> using std::ifstream; 20 using std::ostream; #include <cstdlib> 23 #include "clntdata.h" void outputline( ostream&, const clientdata & ); int main() 28 { 29 ifstream incredit( "credit.dat", ios::in ); if (!incredit ) { 32 cerr << "File could not be opened." << endl; Deitel exit( & Associates, 1 ); Inc. All rights reserved. 1. Load he ade r 1.1 Initialize ifstream obje ct 1.2 Che ck for file ope n

29 34 } cout << setiosflags( ios::left ) << setw( 10 ) << "Account" 37 << setw( 16 ) << "Last Name" << setw( 11 ) 38 << "First Name" << resetiosflags( ios::left ) 39 << setw( 10 ) << "Balance" << endl; clientdata client; incredit.read( reinterpret_cast<char *>( &client ), 44 sizeof( clientdata ) ); while ( incredit &&!incredit.eof() ) { if ( client.accountnumber!= 0 ) 49 outputline( cout, client ); incredit.read( reinterpret_cast<char *>( &client ), 52 sizeof( clientdata ) ); 53 } return 0; Uses eof function to test for the 56 } end of file void outputline( ostream &output, const clientdata &c ) 59 { 60 output << setiosflags( ios::left ) << setw( 10 ) 61 << c.accountnumber << setw( 16 ) << c.lastname 62 << setw( 11 ) << c.firstname << setw( 10 ) 63 << setprecision( 2 ) << resetiosflags( ios::left ) 64 << setiosflags( ios::fixed ios::showpoint ) 65 << c.balance << '\n'; } Deitel & Associates, Inc. All rights reserved. 1.3 Initialize struct obje ct 2. Re ad in data and Inputs sizeof( put clientdata) it into client bytes and puts it into &client (the memory address 3. of Function client). d e finition Outputs data in client to the screen.

30 Account Last Name First Name Balance 29 Brown Nancy Dunn Stacey Barker Doug Smith Dave Stone Sam Prog ram Output

31 14.11 Exam ple : A Transaction Proce ssing Prog ram The following example uses random access files to achieve instant access processing of a bank s account information. We will update existing accounts add new accounts delete accounts store a formatted listing of all accounts in a text file

32 1 // Fig : fig14_15.cpp 2 // This program reads a random access file sequentially, 3 // updates data already written to the file, creates new 4 // data to be placed in the file, and deletes data 5 // already in the file. 6 #include <iostream> 7 8 using std::cout; 9 using std::cerr; 10 using std::cin; 11 using std::endl; 12 using std::ios; #include <fstream> using std::ofstream; 17 using std::ostream; 18 using std::fstream; #include <iomanip> using std::setiosflags; 23 using std::resetiosflags; 24 using std::setw; 25 using std::setprecision; #include <cstdlib> 28 #include "clntdata.h" int enterchoice(); 31 void textfile( fstream& ); 32 void updaterecord( fstream& ); void Deitel newrecord( & Associates, fstream& Inc. All rights ); reserved. 1. Load he ad e rs 1.1 Function prototype s

33 34 void deleterecord( fstream& ); 35 void outputline( ostream&, const clientdata & ); 36 int getaccount( const char * const ); enum Choices { TEXTFILE = 1, UPDATE, NEW, DELETE, END }; int main() 41 { 42 fstream inoutcredit( "credit.dat", ios::in ios::out ); if (!inoutcredit ) { 45 cerr << "File could not be opened." << endl; 46 exit ( 1 ); 47 } int choice; while ( ( choice = enterchoice() )!= END ) { switch ( choice ) { 54 case TEXTFILE: 55 textfile( inoutcredit ); 56 break; 57 case UPDATE: 58 updaterecord( inoutcredit ); 59 break; 60 case NEW: 61 newrecord( inoutcredit ); 62 break; 63 case DELETE: 64 deleterecord( inoutcredit ); 65 break; Deitel & default: Associates, Inc. All rights reserved. 1.2 e num e ration 1.3 Initialize fstream obje ct 1.4 Te st for file ope n fstream objects can both input and output. 1.5 Initialize variab le Calls function enterchoice 2. while loop and switch state m e nts

34 67 cerr << "Incorrect choice\n"; 68 break; 69 } inoutcredit.clear(); // resets end-of-file indicator 72 } return 0; 75 } // Prompt for and input menu choice 78 int enterchoice() 79 { 80 cout << "\nenter your choice" << endl 81 << "1 - store a formatted text file of accounts\n" 82 << " called \"print.txt\" for printing\n" 83 << "2 - update an account\n" 84 << "3 - add a new account\n" 85 << "4 - delete an account\n" 86 << "5 - end program\n? "; int menuchoice; 89 cin >> menuchoice; 90 return menuchoice; 91 } // Create formatted text file for printing 94 void textfile( fstream &readfromfile ) 95 { 96 ofstream outprintfile( "print.txt", ios::out ); if (!outprintfile ) { 99 cerr << "File could not be opened." << endl; Deitel exit( & Associates, 1 ); Inc. All rights reserved. 3. Function d e finitions Opens or creates print.txt

35 101 } outprintfile << setiosflags( ios::left ) << setw( 10 ) 104 << "Account" << setw( 16 ) << "Last Name" << setw( 11 ) 105 << "First Name" << resetiosflags( ios::left ) 106 << setw( 10 ) << "Balance" << endl; 107 readfromfile.seekg( 0 ); clientdata client; 110 readfromfile.read( reinterpret_cast<char *>( &client ), 111 sizeof( clientdata ) ); while (!readfromfile.eof() ) { 114 if ( client.accountnumber!= 0 ) 115 outputline( outprintfile, client ); readfromfile.read( reinterpret_cast<char *>( &client ), 118 sizeof( clientdata ) ); 119 } 120} // Update an account's balance 123void updaterecord( fstream &updatefile ) 124{ 125 int account = getaccount( "Enter account to update" ); updatefile.seekg( ( account - 1 ) * sizeof( clientdata ) ); clientdata client; 130 updatefile.read( reinterpret_cast<char *>( &client ), 131 sizeof( clientdata ) ); Deitel if ( & client.accountnumber Associates, Inc. All rights reserved.!= 0 ) { Outputs formatted data to print.txt 3. Function d e finitions Moves to proper location in file based upon account number. Input data to client

36 134 outputline( cout, client ); 135 cout << "\nenter charge (+) or payment (-): "; double transaction; // charge or payment 138 cin >> transaction; // should validate 139 client.balance += transaction; 140 outputline( cout, client ); 141 updatefile.seekp( ( account-1 ) * sizeof( clientdata ) ); 142 updatefile.write( 143 reinterpret_cast<const char *>( &client ), 144 sizeof( clientdata ) ); 145 } 146 else 147 cerr << "Account #" << account 148 << " has no information." << endl; 149} // Create and insert new record 152void newrecord( fstream &insertinfile ) 153{ 154 int account = getaccount( "Enter new account number" ); insertinfile.seekg( ( account-1 ) * sizeof( clientdata ) ); clientdata client; 159 insertinfile.read( reinterpret_cast<char *>( &client ), 160 sizeof( clientdata ) ); if ( client.accountnumber == 0 ) { 163 cout << "Enter lastname, firstname, balance\n? "; 164 cin >> client.lastname >> client.firstname 165 >> client.balance; 166 client.accountnumber = account; Deitel insertinfile.seekp( & Associates, Inc. All rights ( reserved. account - 1 ) * 3. Function d e finitions Modify account balance, find proper location in file, and write to file. Create a new record. Check if account exists. Input data. Position pointer

37 168 sizeof( clientdata ) ); 169 insertinfile.write( 170 reinterpret_cast<const char *>( &client ), 171 sizeof( clientdata ) ); 172 } 173 else 174 cerr << "Account #" << account 175 << " already contains information." << endl; 176} // Delete an existing record 179void deleterecord( fstream &deletefromfile ) 180{ 181 int account = getaccount( "Enter account to delete" ); deletefromfile.seekg( (account-1) * sizeof( clientdata ) ); clientdata client; 186 deletefromfile.read( reinterpret_cast<char *>( &client ), 187 sizeof( clientdata ) ); if ( client.accountnumber!= 0 ) { 190 clientdata blankclient = { 0, "", "", 0.0 }; deletefromfile.seekp( ( account - 1) * 193 sizeof( clientdata ) ); 194 deletefromfile.write( 195 reinterpret_cast<const char *>( &blankclient ), 196 sizeof( clientdata ) ); 197 cout << "Account #" << account << " deleted." << endl; Deitel } & Associates, Inc. All rights reserved. Write new data to file 3. Function d e finitions Delete record by replacing it with an empty account.

38 199 else 200 cerr << "Account #" << account << " is empty." << endl; 201} // Output a line of client information 204void outputline( ostream &output, const clientdata &c ) 205{ 206 output << setiosflags( ios::left ) << setw( 10 ) 207 << c.accountnumber << setw( 16 ) << c.lastname 208 << setw( 11 ) << c.firstname << setw( 10 ) 209 << setprecision( 2 ) << resetiosflags( ios::left ) 210 << setiosflags( ios::fixed ios::showpoint ) 211 << c.balance << '\n'; 212} // Get an account number from the keyboard 215int getaccount( const char * const prompt ) 216{ 217 int account; do { 220 cout << prompt << " (1-100): "; 221 cin >> account; 222 } while ( account < 1 account > 100 ); return account; 225} 3. Function d e finitions Formatted output.

39 AFTER OPTION 1 PRINT.TXT CONTAINS: Account Last Name First Name Balance 29 Brown Nancy Dunn Stacey Barker Doug Smith Dave Stone Sam Prog ram Output Enter account to update (1-100): Barker Doug 0.00 Enter charge (+) or payment (-): Barker Doug Enter new account number (1-100): 22 Enter lastname, firstname, balance? Johnston Sarah Enter account to delete (1-100): 29 Account #29 deleted.

40 14.12 Input/ Output of Obje cts W hen object data m em bers output to a disk file lose the object s type inform ation only have data bytes Possible solution precede object output by specifying its type

Fundamentals of Programming Session 27

Fundamentals of Programming Session 27 Fundamentals of Programming Session 27 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Fundamentals of Programming Session 28

Fundamentals of Programming Session 28 Fundamentals of Programming Session 28 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Chapter 8 File Processing

Chapter 8 File Processing Chapter 8 File Processing Outline 1 Introduction 2 The Data Hierarchy 3 Files and Streams 4 Creating a Sequential Access File 5 Reading Data from a Sequential Access File 6 Updating Sequential Access Files

More information

Lecture 9. Introduction

Lecture 9. Introduction Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005 Introduction 2 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical

More information

Lecture6 File Processing

Lecture6 File Processing 1 Lecture6 File Processing Dr. Serdar ÇELEBİ 2 Introduction The Data Hierarchy Files and Streams Creating a Sequential Access File Reading Data from a Sequential Access File Updating Sequential Access

More information

Chapter 11 File Processing

Chapter 11 File Processing 1 Chapter 11 File Processing Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 11 File Processing Outline 11.1 Introduction 11.2 The Data Hierarchy 11.3

More information

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 8 Data Files Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To be able to create, read, write and update

More information

C++ Programming Lecture 10 File Processing

C++ Programming Lecture 10 File Processing C++ Programming Lecture 10 File Processing By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Outline Introduction. The Data Hierarchy. Files and Streams. Creating a Sequential

More information

Ch 11. C File Processing (review)

Ch 11. C File Processing (review) Ch 11 C File Processing (review) OBJECTIVES To create, read, write and update files. Sequential access file processing. Data Hierarchy Data Hierarchy: Bit smallest data item Value of 0 or 1 Byte 8 bits

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Exception Handling, File Processing Lecture 11 March 30, 2004 Introduction 2 Exceptions Indicates problem occurred in program Not common An "exception" to a

More information

Fundamentals of Programming Session 25

Fundamentals of Programming Session 25 Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

File Processing. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan File Processing Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline 11.2 The Data Hierarchy 11.3 Files and Streams 11.4 Creating a Sequential

More information

C: How to Program. Week /June/18

C: How to Program. Week /June/18 C: How to Program Week 17 2007/June/18 1 Chapter 11 File Processing Outline 11.1 Introduction 11.2 The Data Hierarchy 11.3 Files and Streams 11.4 Creating a Sequential Access File 11.5 Reading Data from

More information

Chapter 12. Files (reference: Deitel s chap 11) chap8

Chapter 12. Files (reference: Deitel s chap 11) chap8 Chapter 12 Files (reference: Deitel s chap 11) 20061025 chap8 Introduction of File Data files Can be created, updated, and processed by C programs Are used for permanent storage of large amounts of data

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 In Fig. 17.4, the file is to be opened for output, so an ofstream object is created. Two arguments are passed to the object s constructor the filename and the file-open mode (line 12). For an ofstream

More information

C File Processing: One-Page Summary

C File Processing: One-Page Summary Chapter 11 C File Processing C File Processing: One-Page Summary #include int main() { int a; FILE *fpin, *fpout; if ( ( fpin = fopen( "input.txt", "r" ) ) == NULL ) printf( "File could not be

More information

After going through this lesson, you would be able to: store data in a file. access data record by record from the file. move pointer within the file

After going through this lesson, you would be able to: store data in a file. access data record by record from the file. move pointer within the file 16 Files 16.1 Introduction At times it is required to store data on hard disk or floppy disk in some application program. The data is stored in these devices using the concept of file. 16.2 Objectives

More information

C++ How to Program 14.6

C++ How to Program 14.6 C++ How to Program 14.6 14.6 Random-Access Files pg.611-pg.612 -Unlike sequential files, R.A. files are instant-access applications. Any transaction-processing system. Requiring rapid access to specific

More information

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

Convenient way to deal large quantities of data. Store data permanently (until file is deleted). FILE HANDLING Why to use Files: Convenient way to deal large quantities of data. Store data permanently (until file is deleted). Avoid typing data into program multiple times. Share data between programs.

More information

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files. C++ PROGRAMMING LANGUAGE: NAMESPACE AND MANGEMENT OF INPUT/OUTPUT WITH C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of namespace. We also describe how to manage input and output with C++

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Data that is formatted and written to a sequential file as shown in Section 17.4 cannot be modified without the risk of destroying other data in the file. For example, if the name White needs to be changed

More information

Object Oriented Programming Using C++ UNIT-3 I/O Streams

Object Oriented Programming Using C++ UNIT-3 I/O Streams File - The information / data stored under a specific name on a storage device, is called a file. Stream - It refers to a sequence of bytes. Text file - It is a file that stores information in ASCII characters.

More information

C++ files and streams. Lec 28-31

C++ files and streams. Lec 28-31 C++ files and streams Lec 28-31 Introduction So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output

More information

Chapter-12 DATA FILE HANDLING

Chapter-12 DATA FILE HANDLING Chapter-12 DATA FILE HANDLING Introduction: A file is a collection of related data stored in a particular area on the disk. Programs can be designed to perform the read and write operations on these files.

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Unit-V File operations

Unit-V File operations Unit-V File operations What is stream? C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs. A C++ stream is a flow of data into or out of a program, such as the

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e Storage of data in variables and arrays is temporary such data is lost when a program terminates. Files are used for permanent retention of data. Computers store files on secondary

More information

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes:

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes: C++ Binary File I/O C++ file input and output are typically achieved by using an object of one of the following classes: ifstream for reading input only. ofstream for writing output only. fstream for reading

More information

Lecture 5 Files and Streams

Lecture 5 Files and Streams Lecture 5 Files and Streams Introduction C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file,

More information

CS2141 Software Development using C/C++ Stream I/O

CS2141 Software Development using C/C++ Stream I/O CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make

More information

Fall 2017 CISC/CMPE320 9/27/2017

Fall 2017 CISC/CMPE320 9/27/2017 Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader

More information

Introduction. Lecture 5 Files and Streams FILE * FILE *

Introduction. Lecture 5 Files and Streams FILE * FILE * Introduction Lecture Files and Streams C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file, and

More information

Random File Access. 1. Random File Access

Random File Access. 1. Random File Access Random File Access 1. Random File Access In sequential file access, the file is read or written sequentially from the beginning. In random file access, you can skip around to various points in the file

More information

Chapter 12: Advanced File Operations

Chapter 12: Advanced File Operations Chapter 12: Advanced File Operations 12.1 File Operations File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to files Used in many applications:

More information

Streams in C++ Stream concept. Reference information. Stream type declarations

Streams in C++ Stream concept. Reference information. Stream type declarations Stream concept A stream represent a sequence of bytes arriving, being retrieved, being stored, or being sent, in order. A stream is continuos and offer sequential access to the data. Each byte can be read

More information

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] LEARNING OBJECTIVES Upon completion, you should be able to: o define C++ text files o explain the benefits of using I/O file processing o explain

More information

Advanced File Operations. Review of Files. Declaration Opening Using Closing. CS SJAllan Chapter 12 2

Advanced File Operations. Review of Files. Declaration Opening Using Closing. CS SJAllan Chapter 12 2 Chapter 12 Advanced File Operations Review of Files Declaration Opening Using Closing CS 1410 - SJAllan Chapter 12 2 1 Testing for Open Errors To see if the file is opened correctly, test as follows: in.open("cust.dat");

More information

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York CSc 10200 Introduc/on to Compu/ng Lecture 19 Edgardo Molina Fall 2011 City College of New York 18 Standard Device Files Logical file object: Stream that connects a file of logically related data to a program

More information

Chapter 14 Sequential Access Files

Chapter 14 Sequential Access Files Chapter 14 Sequential Access Files Objectives Create file objects Open a sequential access file Determine whether a sequential access file was opened successfully Write data to a sequential access file

More information

STRUCTURES & FILE IO

STRUCTURES & FILE IO STRUCTURES & FILE IO Structures Collections of related variables (aggregates) under one name Can contain variables of different data types Commonly used to define records to be stored in files Combined

More information

Consider the following example where a base class has been derived by other two classes:

Consider the following example where a base class has been derived by other two classes: Class : BCA 3rd Semester Course Code: BCA-S3-03 Course Title: Object Oriented Programming Concepts in C++ Unit IV Polymorphism The word polymorphism means having many forms. Typically, polymorphism occurs

More information

Advanced I/O Concepts

Advanced I/O Concepts Advanced Object Oriented Programming Advanced I/O Concepts Seokhee Jeon Department of Computer Engineering Kyung Hee University jeon@khu.ac.kr 1 1 Streams Diversity of input sources or output destinations

More information

10/23/02 21:20:33 IO_Examples

10/23/02 21:20:33 IO_Examples 1 Oct 22 22:07 2000 extractor1.c Page 1 istream &operator>>( istream &in, Point &p ){ char junk; in >> junk >> p.x >> junk >> p.y >> junk; return in; 2 Oct 22 22:07 2000 extractor2.c Page 1 istream &operator>>(

More information

Streams contd. Text: Chapter12, Big C++

Streams contd. Text: Chapter12, Big C++ Streams contd pm_jat@daiict.ac.in Text: Chapter12, Big C++ Streams Objects are Abstracted Wrapper around input/output source/destinations Steps in reading/writing streams- Open: Establish connection between

More information

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Arrays 3. Declaring Arrays 4. Examples Using Arrays 5. Multidimensional Arrays 6. Multidimensional Arrays Examples 7. Examples Using

More information

Developed By : Ms. K. M. Sanghavi

Developed By : Ms. K. M. Sanghavi Developed By : Ms. K. M. Sanghavi Designing Our Own Manipulators We can design our own manipulators for certain special purpose.the general form for creating a manipulator without any arguments is: ostream

More information

Chapte t r r 9

Chapte t r r 9 Chapter 9 Session Objectives Stream Class Stream Class Hierarchy String I/O Character I/O Object I/O File Pointers and their manipulations Error handling in Files Command Line arguments OOPS WITH C++ Sahaj

More information

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion

More information

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

C++ As A Better C Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2013 Fall Outline 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.5

More information

UEE1303(1070) S 12 Object-Oriented Programming in C++

UEE1303(1070) S 12 Object-Oriented Programming in C++ Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1303(1070) S 12 Object-Oriented Programming in C++ Lecture 06: Streams and File Input/Output I/O stream istream and ostream member

More information

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion

More information

C++ does not, as a part of the language, define how data are sent out and read into the program

C++ does not, as a part of the language, define how data are sent out and read into the program Input and Output C++ does not, as a part of the language, define how data are sent out and read into the program I/O implementation is hardware dependent The input and output (I/O) are handled by the standard

More information

Object Oriented Programming In C++

Object Oriented Programming In C++ C++ Question Bank Page 1 Object Oriented Programming In C++ 1741059 to 1741065 Group F Date: 31 August, 2018 CIA 3 1. Briefly describe the various forms of get() function supported by the input stream.

More information

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 12 Streams and File I/O Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag

More information

ios ifstream fstream

ios ifstream fstream File handling in C++ In most of the real time programming problems we need to store the data permanently on some secondary storage device so that it can be used later. Whenever we have to store the data

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 The C++ standard libraries provide an extensive set of input/output capabilities. C++ uses type-safe I/O. Each I/O operation is executed in a manner sensitive to the data type. If an I/O member function

More information

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents File I/O 1 File Names and Types A file name should reflect its contents Payroll.dat Students.txt Grades.txt A file s extension indicates the kind of data the file holds.dat,.txt general program input or

More information

IS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class

IS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class IS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class Name: A. Fill in the blanks in each of the following statements [Score: 20]: 1. A base class s members can be accessed only

More information

ENG120. Misc. Topics

ENG120. Misc. Topics ENG120 Misc. Topics Topics Files in C Using Command-Line Arguments Typecasting Working with Multiple source files Conditional Operator 2 Files and Streams C views each file as a sequence of bytes File

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Introduction 2 IS 0020 Program Design and Software Tools File Processing, Standard Template Library Lecture 10 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical

More information

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 12 Streams and File I/O Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output,

More information

Object Oriented Programming CS250

Object Oriented Programming CS250 Object Oriented Programming CS250 Abas Computer Science Dept, Faculty of Computers & Informatics, Zagazig University arabas@zu.edu.eg http://www.arsaliem.faculty.zu.edu.eg Object Oriented Programming Principles

More information

Study Material for Class XII. Data File Handling

Study Material for Class XII. Data File Handling Study Material for Class XII Page 1 of 5 Data File Handling Components of C++ to be used with handling: Header s: fstream.h Classes: ifstream, ofstream, fstream File modes: in, out, in out Uses of cascaded

More information

2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator 2.11 Assignment Operators 1 Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator Statements of the form variable = variable operator expression;

More information

Chapter 12 - Templates

Chapter 12 - Templates Chapter 12 - Templates O utline 12.1 Introd uction 12.2 Function Te m plate s 12.3 Ove rload ing Te m plate Functions 12.4 Class Te m p late s 12.5 Class Te m plate s and Non-type Param e te rs 12.6 Te

More information

Chapter 18 - C++ Operator Overloading

Chapter 18 - C++ Operator Overloading Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend

More information

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*...

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*... Input/output Remember std::ostream? namespace std { class ostream { /*... */ }; } extern istream cin; extern ostream cout; extern ostream cerr; extern ostream clog; 7 / 24 std::istream std::ostream std

More information

A stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions

A stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions Topic: File input/output I. Streams II. Access methods III. C++ style Input, output, random access Stream classes: ifstream, ofstream IV. C style The FILE data type Opening files Writing to, reading text

More information

DATA FILE HANDLING FILES. characters (ASCII Code) sequence of bytes, i.e. 0 s & 1 s

DATA FILE HANDLING FILES. characters (ASCII Code) sequence of bytes, i.e. 0 s & 1 s DATA FILE HANDLING The Language like C/C++ treat everything as a file, these languages treat keyboard, mouse, printer, Hard disk, Floppy disk and all other hardware as a file. In C++, a file, at its lowest

More information

CS201 Solved MCQs.

CS201 Solved MCQs. 15.1 Answer each of the following: a. Input/output in C++ occurs as of bytes. b. The stream manipulators that format justification are, and. c. Member function can be used to set and reset format state.

More information

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file. File Structures Physical Files and Logical Files Chap 2. Fundamental File Processing Operations Things you have to learn Physical files and logical files File processing operations: create, open, close,

More information

Generate error the C++ way

Generate error the C++ way Reference informa9on Lecture 3 Stream I/O Consult reference for complete informa9on! UNIX man- pages (available on exam): man topic man istream man ostream ios, basic_string, stringstream, ctype, numeric_limits

More information

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay Input and Output Data Processing Course, I. Hrivnacova, IPN Orsay Output to the Screen Input from the Keyboard IO Headers Output to a File Input from a File Formatting I. Hrivnacova @ Data Processing Course

More information

Streams - Object input and output in C++

Streams - Object input and output in C++ Streams - Object input and output in C++ Dr. Donald Davendra Ph.D. Department of Computing Science, FEI VSB-TU Ostrava Dr. Donald Davendra Ph.D. (Department of Computing Streams - Object Science, input

More information

Stream States. Formatted I/O

Stream States. Formatted I/O C++ Input and Output * the standard C++ library has a collection of classes that can be used for input and output * most of these classes are based on a stream abstraction, the input or output device is

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Course Title: Object Oriented Programming Full Marks: 60 20 20 Course No: CSC161 Pass Marks: 24 8 8 Nature of Course: Theory Lab Credit Hrs: 3 Semester: II Course Description:

More information

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams

More information

Module 11 The C++ I/O System

Module 11 The C++ I/O System Table of Contents Module 11 The C++ I/O System CRITICAL SKILL 11.1: Understand I/O streams... 2 CRITICAL SKILL 11.2: Know the I/O class hierarchy... 3 CRITICAL SKILL 11.3: Overload the > operators...

More information

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

File Operations. Lecture 16 COP 3014 Spring April 18, 2018 File Operations Lecture 16 COP 3014 Spring 2018 April 18, 2018 Input/Ouput to and from files File input and file output is an essential in programming. Most software involves more than keyboard input and

More information

UNIT V FILE HANDLING

UNIT V FILE HANDLING UNIT V CONTENTS: Streams and formatted I/O I/O manipulators File handling Random access Object serialization Namespaces Std namespace ANSI String Objects Standard template library FILE HANDLING Streams:

More information

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-3 6.1 Streams and Basic File I/O I/O Streams I/O

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

PIC10B/1 Winter 2014 Exam I Study Guide

PIC10B/1 Winter 2014 Exam I Study Guide PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand

More information

Writing a Good Program. 7. Stream I/O

Writing a Good Program. 7. Stream I/O Writing a Good Program 1 Input and Output I/O implementation is hardware dependent C++ does not, as a part of the language, define how data are sent out and read into the program The input and output (I/O)

More information

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure Computer Systems Computer System Computer Structure C++ Environment Imperative vs. object-oriented programming in C++ Input / Output Primitive data types Software Banking System Compiler Music Player Text

More information

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. Outline Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. 1 Arrays I Array One type of data structures. Consecutive group of memory locations

More information

System Design and Programming II

System Design and Programming II System Design and Programming II CSCI 194 Section 01 CRN: 10968 Fall 2017 David L. Sylvester, Sr., Assistant Professor Chapter 12 Advanced File Operation File Operations A file is a collection of data

More information

Chapter 12. Streams and File I/O

Chapter 12. Streams and File I/O Chapter 12 Streams and File I/O Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag settings Introduction Streams Special objects Deliver

More information

Chapter 3 - Notes Input/Output

Chapter 3 - Notes Input/Output Chapter 3 - Notes Input/Output I. I/O Streams and Standard I/O Devices A. I/O Background 1. Stream of Bytes: A sequence of bytes from the source to the destination. 2. 2 Types of Streams: i. Input Stream:

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING QUESTION BANK DEPARTMENT:EEE SEMESTER: V SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING UNIT III PART - A (2 Marks) 1. What are the advantages of using exception handling? (AUC MAY 2013) In C++,

More information

BITG 1113: Files and Stream LECTURE 10

BITG 1113: Files and Stream LECTURE 10 BITG 1113: Files and Stream LECTURE 10 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of input & output files. 2. Use data files for input & output

More information

for (int i = 1; i <= 3; i++) { do { cout << "Enter a positive integer: "; cin >> n;

for (int i = 1; i <= 3; i++) { do { cout << Enter a positive integer: ; cin >> n; // Workshop 1 #include using namespace std; int main () int n, k; int sumdigits; for (int i = 1; i n; cin.clear (); cin.ignore (100,

More information

Objects and streams and files CS427: Elements of Software Engineering

Objects and streams and files CS427: Elements of Software Engineering Objects and streams and files CS427: Elements of Software Engineering Lecture 6.2 (C++) 10am, 13 Feb 2012 CS427 Objects and streams and files 1/18 Today s topics 1 Recall...... Dynamic Memory Allocation...

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

Streams. Rupesh Nasre.

Streams. Rupesh Nasre. Streams Rupesh Nasre. OOAIA January 2018 I/O Input stream istream cin Defaults to keyboard / stdin Output stream ostream cout std::string name; std::cout > name; std::cout

More information