Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Object Oriented Programming          File Handling           LECTURE-32, 33  1
FILE HANDLING2
Introduction    All programs we looked earlier:          input data from the keyboard.          output data to the scre...
Streams Usage We’ve used streams already  cin     Input from stream object connected to      keyboard  cout     Outpu...
File input and output streams                                5
Streams     File Input Stream – reads data from disk      file to the program.      File output Stream – writes data to ...
Stream Classes                 7
The Data Hierarchy From smallest to largest   Bit (binary digit)      1 or 0      Everything in computer ultimately re...
The Data Hierarchy (contd.) From smallest to largest (continued)    Field: group of characters with some meaning        ...
General File I/O Steps• Declare a file name variable• Associate the file name variable with  the disk file name• Open the ...
Files and Streams C++ views file as sequence of bytes   Ends with end-of-file marker       0   1   2   3   4   5   6   7...
Creating a Sequential-Access File C++ imposes no structure on file    Concept of "record" must be implemented by program...
Creating a Sequential-Access File File-open modes                                      13
Creating a Sequential-Access File Operations    Overloaded operator!       !outClientFile       Returns nonzero (true)...
// Create a sequential file.#include <iostream>#include <fstream>using namespace std;int main() {    // ofstream construct...
cout << "Enter the account, name, and balance." << endl     << "Enter ’N’ to end input.n? ";   int account;   char name[ 3...
Enter the account, name, and balance.Enter ‘N’ to end input.100 Jones 24.98? Y200 Doe 345.67? Y300 White 0.00? Y400 Stone ...
Reading Data from a Sequential-AccessFile Reading files   ifstream inClientFile( "filename", ios::in );   Overloaded ! ...
const int ZERO = 0, CREDIT = 1, DEBIT = 2, END = 3;int main(){  // ifstream constructor opens the file  ifstream inClientF...
// process users requestwhile ( request != END ) { switch ( request ) {   case ZERO:     cout << "nAccounts with zero bala...
// read account, name and balance from file inClientFile >> account >> name >> balance; // display file contents (until eo...
// getRequest function definition  int getRequest()       {          int choice;        cout<<“Enter 0 to see zero balance...
Reading Data from a Sequential-AccessFile File position pointers    Files have "get" and "put" pointers       Index of ...
Reading Data from a Sequential-AccessFile Examples    fileObject.seekg(0)      Goes to start of file (location 0) becau...
Reading Data from a Sequential-AccessFile To find pointer location   tellg and tellp   int location = fileObject.tellg(...
Storage in Sequential-Access File "1234567" (char *) vs 1234567 (int)    char * takes 7 bytes (1 for each character)   ...
Updating Sequential-Access Files Updating sequential files    Risk overwriting other data    Example: change name "Whit...
Random-Access Files Instant access   Want to locate record quickly      Airline reservations, Banking system, ATMs   S...
Random-Access Files C++ imposes no structure on files   Programmer must create random-access files   Fixed-length recor...
<< operator vs. write() outFile << number   Outputs number (int) as a char *   Variable number of bytes outFile.write(...
Creating a Random-Access File ExampleoutFile.write( reinterpret_cast<const char *>(&number),   sizeof( number ) );    &n...
Creating a Random-Access File Problem statement    Credit processing program    Record      Account number (key)      ...
Upcoming SlideShare
Loading in …5
×

file handling c++

45,609 views

Published on

Published in: Education
  • I can definitely recommend a website that really helped me with my essay. I found out it was due the day before I had to submit it. Went into full-on panic mode. Worst experience of my senior year by far. It’s called ⇒ www.HelpWriting.net ⇐. The quality of the writing is passable but the completion rate is super quick. You get to pick your own writer to do your stuff and that’s also a big bonus.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Hello! I can recommend a site that has helped me. It's called HelpWriting.net They helped me for writing my quality research paper on diabetes, and of course by keeping my all other needs fulfilled.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Dating direct: ♥♥♥ http://bit.ly/2F7hN3u ♥♥♥
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Dating for everyone is here: ❤❤❤ http://bit.ly/2F7hN3u ❤❤❤
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy &amp; Proven Way to Build Good Habits &amp; Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

file handling c++

  1. 1. Object Oriented Programming File Handling LECTURE-32, 33 1
  2. 2. FILE HANDLING2
  3. 3. Introduction All programs we looked earlier:  input data from the keyboard.  output data to the screen. Output would be lost as soon as weexit from the program. How do we store data permanently?  We can use secondary storage device.  Data is packaged up on the storage device as data structures called files. 3
  4. 4. Streams Usage We’ve used streams already cin Input from stream object connected to keyboard cout Output to stream object connected to screen Can define other streams To or from files 4 Used similarly as cin, cout
  5. 5. File input and output streams 5
  6. 6. Streams File Input Stream – reads data from disk file to the program. File output Stream – writes data to thedisk file from the program. The I/O system of C++ contains:  ifstream – provides input operations on files  ofstream – provides output operations on files  fstream – supports for simultaneous input and output operations on files 6
  7. 7. Stream Classes 7
  8. 8. The Data Hierarchy From smallest to largest  Bit (binary digit)  1 or 0  Everything in computer ultimately represented as bits  Character set  Digits, letters, symbols used to represent data  Every character represented by 1s and 0s  Byte: 8 bits  Can store a character (char) 8
  9. 9. The Data Hierarchy (contd.) From smallest to largest (continued)  Field: group of characters with some meaning e.g., Your name  Record: group of related fields struct or class in C++ In payroll system, could be name, S#, 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  Database: group of related files Payroll, accounts-receivable, inventory… 9
  10. 10. General File I/O Steps• Declare a file name variable• Associate the file name variable with the disk file name• Open the file• Use the file• Close the file 10
  11. 11. Files and Streams C++ views file as sequence of bytes  Ends with end-of-file marker 0 1 2 3 4 5 6 7 8 9 ... n-1 ... end-of-file marker 11
  12. 12. 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); 12
  13. 13. Creating a Sequential-Access File File-open modes 13
  14. 14. Creating a Sequential-Access File Operations  Overloaded operator! !outClientFile Returns nonzero (true) if some error Opening non-existent file for reading, no permissions, disk full etc.  Writing to file (just like cout) outClientFile << myVariable  Closing file outClientFile.close() Automatically closed when destructor called 14
  15. 15. // Create a sequential file.#include <iostream>#include <fstream>using namespace std;int main() { // ofstream constructor opens file ofstream outClientFile( "clients.txt",ios::out ); // exit program if unable to create file if ( !outClientFile ) { // overloaded ! operator cout << "File could not be opened" << endl; exit( 1 );} // end if 15
  16. 16. cout << "Enter the account, name, and balance." << endl << "Enter ’N’ to end input.n? "; int account; char name[ 30 ], ch=‘y’; double balance; // read account, name and balance from cin, then place in file while (ch == ‘y’) { cin >> account >> name >> balance; outClientFile << account << << name << << balance << endl; cout << "? "; cin>>ch; } // end while return 0; // ofstream destructor closes file 16} // end main
  17. 17. Enter the account, name, and balance.Enter ‘N’ to end input.100 Jones 24.98? Y200 Doe 345.67? Y300 White 0.00? Y400 Stone -42.16? Y500 Rich 224.62? N 17
  18. 18. Reading Data from a Sequential-AccessFile Reading files  ifstream inClientFile( "filename", ios::in );  Overloaded !  !inClientFile tests if file was opened properly Upcoming example  Credit manager program  List accounts with zero balance, credit, and debit 18
  19. 19. const int ZERO = 0, CREDIT = 1, DEBIT = 2, END = 3;int main(){ // ifstream constructor opens the file ifstream inClientFile( "clients.txt", ios::in ); // exit program if ifstream could not open file if ( !inClientFile ) { cout << "File could not be opened" << endl; exit( 1 ); } // end if int request; int account; char name[ 30 ]; double balance; // get users request (e.g., zero, credit or debit balance) 19 request = getRequest();
  20. 20. // process users requestwhile ( request != END ) { switch ( request ) { case ZERO: cout << "nAccounts with zero balances:n"; break; case CREDIT: cout << "nAccounts with credit balances:n"; break; case DEBIT: cout << "nAccounts with debit balances:n"; break; 20 } // end switch
  21. 21. // read account, name and balance from file inClientFile >> account >> name >> balance; // display file contents (until eof) while ( !inClientFile.eof() ) { // display record if ( shouldDisplay( request, balance ) ) cout << account << ‘ ’<<name << ‘ ’<< balance << endl; // read account, name and balance from file inClientFile >> account >> name >> balance; } // end inner while inClientFile.clear(); // reset eof for next input inClientFile.seekg( 0 ); // move to beginning of file request = getRequest(); // get additional request from user} // end outer while 21
  22. 22. // getRequest function definition int getRequest() { int choice; cout<<“Enter 0 to see zero balance accounts”<<endl; cout<<“Enter 1 to see credit balance accounts”<<endl; cout<<“Enter 2 to see debit balance accounts”<<endl; cout<<“Enter 3 to end the program”<<endl; cin>>choice; return choice; }// shouldDisplay function definition bool shouldDisplay(int req, double bal) { if( (req == ZERO && bal == 0) || (req == CREDIT && bal < 0) || (req == DEBIT && bal > 0) ) return true; 22 else return false; }
  23. 23. Reading Data from a Sequential-AccessFile File position pointers  Files have "get" and "put" pointers  Index 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  Direction (ios::beg default)  ios::beg - relative to beginning of stream  ios::cur - relative to current position  ios::end - relative to end  Offset: number of bytes relative to direction 23
  24. 24. Reading Data from a Sequential-AccessFile Examples  fileObject.seekg(0) Goes to start 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 from current position  fileObject.seekg(y, ios::end) Goes y bytes back from end  fileObject.seekg(0, ios::cur) Goes to last byte 24  seekp similar
  25. 25. Reading Data from a Sequential-AccessFile To find pointer location  tellg and tellp  int location = fileObject.tellg() 25
  26. 26. Storage in Sequential-Access File "1234567" (char *) vs 1234567 (int)  char * takes 7 bytes (1 for each character)  int takes fixed number of bytes 123 same size in bytes as 1234567 << operator  outFile << number Outputs number (int) as a char * Variable number of bytes 26
  27. 27. 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 300 Worthington 0.00 300 White 0.00 400 Jones 32.87 Data gets overwritten 300 Worthington 0.00ones 32.87 27
  28. 28. Random-Access Files Instant access  Want to locate record quickly  Airline reservations, Banking system, ATMs  Sequential files must search through each one Random-access files are solution  Instant access  Update/delete items without changing other data 28
  29. 29. Random-Access Files C++ imposes no structure on files  Programmer must create random-access files  Fixed-length records  Calculate position in file from record size and key 0 100 200 300 400 500 } byte offsets } } } } } } 100 100 100 100 100 100 bytes bytes bytes bytes bytes bytes 29
  30. 30. << operator vs. 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 * 30
  31. 31. Creating a Random-Access File ExampleoutFile.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 when using raw, unformatted data Use ios::binary for raw writes/reads 31
  32. 32. Creating a Random-Access File Problem statement  Credit processing program  Record Account number (key) First and last name Balance  Account operations Update, create new, delete, list all accounts in a fileNext: program to create blank 100-record file 32

×