 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005.

Slides:



Advertisements
Similar presentations
1 Classes and Data Abstraction and File Processing Lecture 13.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - File Processing Outline 14.1 Introduction 14.2 The Data Hierarchy 14.3 Files and Streams.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 13 Advanced.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
CPSC 231 D.H. C++ File Processing 1 Learning Objectives §C++ I/O streams. §Reading and writing sequential files. §Reading and writing random access files.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
 2006 Pearson Education, Inc. All rights reserved File Processing.
計算機概論實習 Files and Streams C++ views file as sequence of bytes Ends with end-of-file marker n-1 end-of-file marker 67 This is.
Copyright © 2012 Pearson Education, Inc. Chapter 12: Advanced File Operations.
 2006 Pearson Education, Inc. All rights reserved File Processing.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
1 File I/O In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
COIT29222-Structured Programming Lecture Week 12  Reading: Textbook (4 th Ed.), Chapter 14 Textbook (6 th Ed.), Chapter 17 Study Guide Book 3, Module.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 14 – File Processing Outline 14.1Introduction 14.2The Data Hierarchy 14.3Files and Streams.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Programming Practice Introduction Tree Operations. Binary Search Tree. File Processing Create, read, write and update files. Sequential.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
 2008 Pearson Education, Inc. All rights reserved File Processing.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - File Processing Outline 14.1 Introduction 14.2 The Data Hierarchy 14.3 Files and Streams.
Outline 1 Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü.
計算機程式語言 Lecture 17-1 國立台灣大學生物機電系 林達德 17 File Processing.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
File I/O. fstream files File: similar to vector of elements Used for input and output Elements of file can be –character (text)struct –object (non-text.
I/O in C++ October 7, Junaed Sattar. Stream I/O a stream is a flow of bytes/characters/ints or any type of data input streams: to the program output.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools File Processing, Standard Template Library Lecture 12 July.
DCT1063 Programming 2 CHAPTER 3 FILE INPUT AND FILE OUTPUT Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Streams, and File I/O Review. STREAMS Review STREAMS Streams are sequences of bytes. C++ I/0 occurs in streams Input – bytes flow from device to memory.
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
1 CSC241: Object Oriented Programming Lecture No 32.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
1 Today’s Objectives  Announcements Homework #5 is due next Monday, July 24. Since this date is so close to the end of the semester, no late assignments.
Learners Support Publications Working with Files.
Binary Files. Text Files vs. Binary Files Text files: A way to store data in a secondary storage device using Text representation (e.g., ASCII characters)
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني I/O and File management(cont.) Binary and random files.
2008YeungNam Univ. SE Lab. 1 C++ views each file as a sequence of bytes terminated by EOF-marker. Header files Files are opened by creating objects of.
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
CS212: Object Oriented Analysis and Design
File Processing.
File Processing.
17 File Processing.
TMF1414 Introduction to Programming
CPSC 231 D.H. C++ File Processing
17 File Processing.
Chapter 14 – File Processing
Chapter 11 – File Processing
17 File Processing.
Chapter 13: Advanced File and I/O Operations
Topics Input and Output Streams More Detailed Error Testing
Chapter 12: Advanced File Operations.
Fundamental of Programming (C)
EPSII 59:006 Spring 2004.
C++ Programming Lecture 8 File Processing
Presentation transcript:

 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005

 2003 Prentice Hall, Inc. All rights reserved. 2 Introduction Storage of data –Arrays, variables are temporary –Files are permanent Magnetic disk, optical disk, tapes In this chapter –Create, update, process files –Sequential and random access –Formatted and raw processing

 2003 Prentice Hall, Inc. All rights reserved. 3 The Data Hierarchy From smallest to largest –Bit (binary digit) 1 or 0 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 ) 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…

 2003 Prentice Hall, Inc. All rights reserved. 4 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 included Communication between program and file/device n-1 end-of-file marker 67

 2003 Prentice Hall, Inc. All rights reserved. 5 Files and Streams To perform file processing –Include and –Class templates basic_ifstream (input) basic_ofstream (output) basic_fstream (I/O) –typedef s for specializations that allow char I/O ifstream ( char input) ofstream ( char output) fstream ( char I/O)

 2003 Prentice Hall, Inc. All rights reserved. 6 Files and Streams Opening files –Create objects from template –Derive from stream classes Can use stream methods : put, get, peek, etc. basic_fstream basic_ios basic_ifstreambasic_ofstreambasic_iostream basic_istreambasic_ostream

 2003 Prentice Hall, Inc. All rights reserved. 7 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);

 2003 Prentice Hall, Inc. All rights reserved. 8 Creating a Sequential-Access File File-open modes –ofstream opened for output by default ofstream outClientFile( "clients.dat", ios::out ); ofstream outClientFile( "clients.dat");

 2003 Prentice Hall, Inc. All rights reserved. 9 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 failbit or badbit set, otherwise nonzero –failbit set when EOF found while ( cin >> myVariable ) –Implicitly converts cin to pointer –Loops until EOF –Writing to file (just like cout ) outClientFile << myVariable –Closing file outClientFile.close() Automatically closed when destructor called

 2003 Prentice Hall, Inc. All rights reserved. Outline 10 fig14_04.cpp (1 of 2) 1 // Fig. 14.4: fig14_04.cpp 2 // Create a sequential file. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::ios; 8 using std::cerr; 9 using std::endl; #include using std::ofstream; #include // exit prototype int main() 18 { 19 // ofstream constructor opens file 20 ofstream outClientFile( "clients.dat", ios::out ); // exit program if unable to create file 23 if ( !outClientFile ) { // overloaded ! operator 24 cerr << "File could not be opened" << endl; 25 exit( 1 ); } // 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.

 2003 Prentice Hall, Inc. All rights reserved. Outline 11 fig14_04.cpp (2 of 2) cout << "Enter the account, name, and balance." << endl 30 << "Enter end-of-file to end input.\n? "; int account; 33 char name[ 30 ]; 34 double balance; // 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 << "? "; } // end while return 0; // ofstream destructor closes file } // end main cin is implicitly converted to a pointer. When EOF is encountered, it returns 0 and the loop stops. Write data to file like a regular stream. File closed when destructor called for object. Can be explicitly closed with close().

 2003 Prentice Hall, Inc. All rights reserved. Outline 12 fig14_04.cpp output (1 of 1) Enter the account, name, and balance. Enter end-of-file to end input. ? 100 Jones ? 200 Doe ? 300 White 0.00 ? 400 Stone ? 500 Rich ? ^Z

 2003 Prentice Hall, Inc. All rights reserved. 13 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 )

 2003 Prentice Hall, Inc. All rights reserved. Outline 14 fig14_07.cpp (2 of 3) 28 int main() 29 { 30 // ifstream constructor opens the file 31 ifstream inClientFile( "clients.dat", ios::in ); // exit program if ifstream could not open file 34 if ( !inClientFile ) { 35 cerr << "File could not be opened" << endl; 36 exit( 1 ); } // end if int account; 41 char name[ 30 ]; 42 double balance; cout << left << setw( 10 ) << "Account" << setw( 13 ) 45 << "Name" << "Balance" << endl << fixed << showpoint; // display each record in file 48 while ( inClientFile >> account >> name >> balance ) 49 outputLine( account, name, balance ); return 0; // ifstream destructor closes the file } // end main Open and test file for input.Read from file until EOF found.

 2003 Prentice Hall, Inc. All rights reserved. Outline 15 fig14_07.cpp (3 of 3) fig14_07.cpp output (1 of 1) // 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; } // end function outputLine Account Name Balance 100 Jones Doe White Stone Rich

 2003 Prentice Hall, Inc. All rights reserved. 16 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) Classes have "get" and "put" pointers –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

 2003 Prentice Hall, Inc. All rights reserved. 17 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 To find pointer location –tellg and tellp –location = fileObject.tellg()

 2003 Prentice Hall, Inc. All rights reserved. 18 Updating Sequential-Access Files Updating sequential files –Risk overwriting other data –Example: change name "White" to "Worthington" Old data 300 White Jones Insert new data –Formatted text different from internal representation –Problem can be avoided, but awkward 300 White Jones Worthington 0.00ones Worthington 0.00 Data gets overwritten

 2003 Prentice Hall, Inc. All rights reserved. 19 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

 2003 Prentice Hall, Inc. All rights reserved. 20 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

 2003 Prentice Hall, Inc. All rights reserved. 21 Creating a Random-Access File " " ( char * ) vs ( int ) –char * takes 8 bytes (1 for each character + null) –int takes fixed number of bytes (perhaps 4) 123 same size in bytes as << 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 *

 2003 Prentice Hall, Inc. All rights reserved. 22 Creating a Random-Access File Example outFile.write( reinterpret_cast (&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 Usually write entire struct or object to file

 2003 Prentice Hall, Inc. All rights reserved. 23 Writing Data Randomly to a Random-Access File Use seekp to write to exact location in file –Where does the first record begin? Byte 0 –The second record? Byte 0 + sizeof(object) –Any record? (Recordnum - 1) * sizeof(object) read - similar to write –Reads raw bytes from file into memory –inFile.read( reinterpret_cast ( &number ), sizeof( int ) ); &number : location to store data sizeof(int) : how many bytes to read –Do not use inFile >> number with raw bytes >> expects char *

 2003 Prentice Hall, Inc. All rights reserved. 24 Input/Output of Objects I/O of objects –Chapter 8 (overloaded >> ) –Only object's data transmitted Member functions available internally –When objects stored in file, lose type info (class, etc.) Program must know type of object when reading –One solution When writing, output object type code before real object When reading, read type code –Call proper overloaded function ( switch )