 2006 Pearson Education, Inc. All rights reserved. 1 17 File Processing.

Slides:



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

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
 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.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
Chapter 8: I/O Streams and Data Files. In this chapter, you will learn about: – I/O file stream objects and functions – Reading and writing character-based.
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.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
(continue) © by Pearson Education, Inc. All Rights Reserved.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
FILE HANDLING IN C++.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005.
 2008 Pearson Education, Inc. All rights reserved File Processing.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
計算機程式語言 Lecture 17-1 國立台灣大學生物機電系 林達德 17 File Processing.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
C++ FILE I/O.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
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
 Pearson Education, Inc. All rights reserved Files and Streams.
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 1 due Friday, 7pm. RAD due next Friday. Presentations week 6. Today: –More details on functions,
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
1 CSC241: Object Oriented Programming Lecture No 32.
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.
FILE HANDLING(WORKING WITH FILES) FILE- A file is a collection of related data stored in a particular area on the disk. STREAMS- interface between the.
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.
Files and Streams Lec Introduction  Files are used for long-term retention of large amounts of data, even after the program that created the.
CS212: Object Oriented Analysis and Design
Chapter 14: Sequential Access Files
File Processing.
11 C File Processing.
17 File Processing.
Chapter 1.2 Introduction to C++ Programming
TMF1414 Introduction to Programming
C ++ MULTIPLE CHOICE QUESTION
CPSC 231 D.H. C++ File Processing
FILE HANDLING IN C++.
17 File Processing.
Chapter 11 – File Processing
MSIS 670: Object-Oriented Software Engineering
17 File Processing.
files Dr. Bhargavi Goswami Department of Computer Science
Topics Input and Output Streams More Detailed Error Testing
Chapter 12: Advanced File Operations.
Fundamental of Programming (C)
C++ Programming Lecture 8 File Processing
Presentation transcript:

 2006 Pearson Education, Inc. All rights reserved File Processing

 2006 Pearson Education, Inc. All rights reserved. 2 OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access file processing.  To use high-performance unformatted I/O operations.  The differences between formatted-data and raw-data file processing.  To build a transaction-processing program using random-access file processing.

 2006 Pearson Education, Inc. All rights reserved. 3 const const objects – Keyword const – Specifies that an object is not modifiable – Attempts to modify the object will result in compilation errors const member functions – Only const member function can be called for const objects – Member functions declared const are not allowed to modify the object – A function is specified as const both in its prototype and in its definition – const declarations are not allowed for constructors and destructors

 2006 Pearson Education, Inc. All rights reserved. 4 Outline Time.h (1 of 2) const keyword to indicate that member function cannot modify the object

 2006 Pearson Education, Inc. All rights reserved. 5 Outline Time.h (2 of 2)

 2006 Pearson Education, Inc. All rights reserved. 6 Outline Time.cpp (1 of 3)

 2006 Pearson Education, Inc. All rights reserved. 7 Outline Time.cpp (2 of 3) const keyword in function definition, as well as in function prototype

 2006 Pearson Education, Inc. All rights reserved. 8 Outline Time.cpp (3 of 3)

 2006 Pearson Education, Inc. All rights reserved. 9 Outline fig10_03.c pp (1 of 2) Cannot invoke non- const member functions on a const object

 2006 Pearson Education, Inc. All rights reserved. 10 Outline fig10_03.c pp (2 of 2)

 2006 Pearson Education, Inc. All rights reserved. 11 this…. Member functions know which object’s data members to manipulate – Every object has access to its own address through a pointer called this (a C++ keyword) – An object’s this pointer is not part of the object itself – The this pointer is passed (by the compiler) as an implicit argument to each of the object’s non- static member functions Objects use the this pointer implicitly or explicitly – Implicitly when accessing members directly – Explicitly when using keyword this – Type of the this pointer depends on the type of the object

 2006 Pearson Education, Inc. All rights reserved. 12 Outline fig10_17.c pp (1 of 2)

 2006 Pearson Education, Inc. All rights reserved. 13 Outline fig10_17.c pp (2 of 2) Implicitly using the this pointer to access member x Explicitly using the this pointer to access member x Using the dereferenced this pointer and the dot operator

 2006 Pearson Education, Inc. All rights reserved. 14 Common Programming Error Attempting to use the member selection operator (. ) with a pointer to an object is a compilation error—the dot member selection operator may be used only with an lvalue such as an object’s name, a reference to an object or a dereferenced pointer to an object.

 2006 Pearson Education, Inc. All rights reserved. 15 Using the this Pointer (Cont.) Cascaded member-function calls – Multiple functions are invoked in the same statement – Enabled by member functions returning the dereferenced this pointer – Example t.setMinute( 30 ).setSecond( 22 ); – Calls t.setMinute( 30 ); – Then calls t.setSecond( 22 );

 2006 Pearson Education, Inc. All rights reserved. 16 Outline Time.h (1 of 2) set functions return Time & to enable cascading

 2006 Pearson Education, Inc. All rights reserved. 17 Outline Time.h (2 of 2)

 2006 Pearson Education, Inc. All rights reserved. 18 Outline Time.cpp (1 of 3) Returning dereferenced this pointer enables cascading

 2006 Pearson Education, Inc. All rights reserved. 19 Outline Time.cpp (2 of 3)

 2006 Pearson Education, Inc. All rights reserved. 20 Outline Time.cpp (3 of 3)

 2006 Pearson Education, Inc. All rights reserved. 21 Outline fig10_20.c pp (1 of 2) Cascaded function calls using the reference returned by one function call to invoke the next Note that these calls must appear in the order shown, because printStandard does not return a reference to t

 2006 Pearson Education, Inc. All rights reserved. 22 Outline fig10_20.c pp (2 of 2)

 2006 Pearson Education, Inc. All rights reserved. 23 Quiz What (if anything) prints when each of the following statements is performed? If the statement contains an error, describe the error and indicate how to correct it. Assume the following variable declarations: char s1[ 50 ] = "jack"; char s2[ 50 ] = "jill"; char s3[ 50 ]; cout << strcpy( s3, s2 ) << endl; cout << strcat( strcat( strcpy( s3, s1 ), " and " ), s2 ) << endl; cout << strlen( s1 ) + strlen( s2 ) << endl; cout << strlen( s3 ) << endl;

 2006 Pearson Education, Inc. All rights reserved File/IO Introduction Files – Used for data persistence Permanent retention of large amounts of data – Stored on secondary storage devices Magnetic disks Optical disks Tapes

 2006 Pearson Education, Inc. All rights reserved The Data Hierarchy Bits (“binary digits”) – Can assume one of two values, 0 or 1 – Smallest data item that computers support Computer circuitry performs simple bit manipulations Ultimately all data items are composed of bits Characters – Include decimal digits, letters and special symbols Composed of bits ( 1 s and 0 s) – A character set is the set of all characters used on a particular computer – char s are stored in bytes (8 bits) – wchar_t s are stored in more than one byte

 2006 Pearson Education, Inc. All rights reserved The Data Hierarchy (Cont.) Fields – Composed of characters – Conveys some meaning – Example Uppercase and lowercase letters can represent a name Records – Composed of several fields – Represented as a class in C++ – Example An employee’s record might include id#, name, address, etc. – A record key is a field unique to each record

 2006 Pearson Education, Inc. All rights reserved. 27 Fig | Data hierarchy.

 2006 Pearson Education, Inc. All rights reserved The Data Hierarchy (Cont.) File – Composed of a group of related records – Example A payroll file containing one record for each employee – Many ways to organize records in a file Such as a sequential file – Records are stored in order by a record-key field Database – Composed of a group of related files – Managed by a collection of programs called a database management system (DBMS)

 2006 Pearson Education, Inc. All rights reserved Files and Streams Files – Viewed by C++ as a sequence of bytes – Ends either with an end-of-file marker or at a system- recorded byte number – Communication between a program and a file is performed through stream objects header file – Stream class templates basic_ifstream – for file input basic_ofstream – for file output basic_fstream – for file input and output – Files are opened by creating objects of stream template specializations

 2006 Pearson Education, Inc. All rights reserved. 30 Fig | C++’s view of a file of n bytes.

 2006 Pearson Education, Inc. All rights reserved. 31 Fig | Portion of stream I/O template hierarchy.

 2006 Pearson Education, Inc. All rights reserved Creating a Sequential File File structure – The programmer must structure files C++ does not impose structures on files

 2006 Pearson Education, Inc. All rights reserved. 33 Outline Fig17_04.cpp (1 of 2) Open file client.dat for output Overloaded operator! will return true if the file did not open successfully

 2006 Pearson Education, Inc. All rights reserved. 34 Outline Fig17_04.cpp (2 of 2) Overloaded operator void * will return the null pointer 0 ( false ) when the user enters the end-of-file indicator Write data to client.dat using the stream insertion operator ofstream destructor implicitly closes the file

 2006 Pearson Education, Inc. All rights reserved Creating a Sequential File (Cont.) Creating an ofstream object – Opens a file for output – Constructor takes two arguments A filename – If the file doe not exist, it is first created A file-open mode – ios::out – the default mode Overwrites preexisting data in the file – ios::app Appends data to the end of the file – Can also use member function open on existing object Takes same arguments as the constructor

 2006 Pearson Education, Inc. All rights reserved. 36 Common Programming Error 17.1 Use caution when opening an existing file for output (ios::out), especially when you want to preserve the file’s contents, which will be discarded without warning.

 2006 Pearson Education, Inc. All rights reserved. 37 Fig | File open modes.

 2006 Pearson Education, Inc. All rights reserved. 38 Common Programming Error 17.2 Not opening a file before attempting to reference it in a program will result in an error.

 2006 Pearson Education, Inc. All rights reserved Creating a Sequential File (Cont.) Using an ofstream object – Writing to the file Use the stream insertion operator – Member function close Releases the file resource Implicitly performed by ofstream ’s destructor ios operators (usable with ofstream ) – Operator member function operator! Returns true if either the failbit or badbit is set – Operator member function operator void * Converts the stream to a pointer – The null pointer if either the failbit or badbit is set

 2006 Pearson Education, Inc. All rights reserved. 40 Fig | End-of-file key combinations for various popular computer systems.

 2006 Pearson Education, Inc. All rights reserved. 41 Performance Tip 17.1 Closing files explicitly when the program no longer needs to reference them can reduce resource usage (especially if the program continues execution after closing the files).

 2006 Pearson Education, Inc. All rights reserved Reading Data from a Sequential File Creating an ifstream object – Opens a file for input – Constructor takes two arguments A filename A file-open mode – ios::in – the default mode Can only read from the file – Can also use member function open on an existing object Takes same arguments as the constructor

 2006 Pearson Education, Inc. All rights reserved. 43 Good Programming Practice 17.1 Open a file for input only (using ios::in) if the file’s contents should not be modified. This prevents unintentional modification of the file’s contents and is an example of the principle of least privilege.

 2006 Pearson Education, Inc. All rights reserved. 44 Outline Fig17_07.cpp (1 of 3)

 2006 Pearson Education, Inc. All rights reserved. 45 Outline Fig17_07.cpp (2 of 3) Open clients.dat for input Overloaded operator void * returns a null pointer 0 ( false ) when the end of clients.dat is reached Overloaded operator! returns true if clients.dat was not opened successfully ifstream destructor implicitly closes the file

 2006 Pearson Education, Inc. All rights reserved. 46 Outline Fig17_07.cpp (3 of 3)

 2006 Pearson Education, Inc. All rights reserved Reading Data from a Sequential File (Cont.) File-position pointer – The byte number of the next byte to be read or written – Member functions seekg and seekp (of istream and ostream, respectively) Repositions the file-position pointer to the specified location – Takes desired offset argument as a long A second argument can specify the seek direction – ios::beg – the default Positioning relative to the beginning – ios::cur Positioning relative to the current position – ios::end Positioning relative to the end

 2006 Pearson Education, Inc. All rights reserved Reading Data from a Sequential File (Cont.) – Member functions seekg and seekp (Cont.) Examples – fileObject.seekg( n ); Position to the nth byte of fileObject – fileObject.seekg( n, ios::cur ); Position n bytes forward in fileobject – fileObject.seekg( n, ios::end ); Position n bytes back from end of fileObject – fileObject.seekg( 0, ios::end ); Position at end of fileObject

 2006 Pearson Education, Inc. All rights reserved Reading Data from a Sequential File (Cont.) File-position pointer (Cont.) – Member functions tellg and tellp (of istream and ostream, respectively) Returns current position of the file-position pointer as type long Example – Location = fileObject.tellg();

 2006 Pearson Education, Inc. All rights reserved. 50 Outline Fig17_08.cpp (1 of 6)

 2006 Pearson Education, Inc. All rights reserved. 51 Outline Fig17_08.cpp (2 of 6)

 2006 Pearson Education, Inc. All rights reserved. 52 Outline Fig17_08.cpp (3 of 6)

 2006 Pearson Education, Inc. All rights reserved. 53 Outline Fig17_08.cpp (4 of 6) Use ostream member function seekg to reposition the file- position pointer to the beginning

 2006 Pearson Education, Inc. All rights reserved. 54 Outline Fig17_08.cpp (5 of 6)

 2006 Pearson Education, Inc. All rights reserved. 55 Outline Fig17_08.cpp (6 of 6)

 2006 Pearson Education, Inc. All rights reserved Updating Sequential Files Updating a record in a sequential file – The new record could be longer than the old record If it is, it could overwrite the next sequential record You would have to rewrite every record into another file – Copy over all records before this one – Write new version of this record – Copy over all records after this one This might be acceptable if you are updating many records

 2006 Pearson Education, Inc. All rights reserved Random-Access Files Random-access files – Necessary for instant-access applications Such as transaction-processing systems – A record can be inserted, deleted or modified without affecting other records – Various techniques can be used Require that all records be of the same length, arranged in the order of the record keys – Program can calculate the exact location of any record Base on the record size and record key

 2006 Pearson Education, Inc. All rights reserved. 58 Fig | C++ view of a random-access file.

 2006 Pearson Education, Inc. All rights reserved Creating a Random-Access File ostream member function write – Writes a number of bytes from a location in memory to the stream If the stream is associated with a file, the writing is at the “put” file-position pointer – First argument A const char * pointing to bytes in memory – Second argument A size_t specifying the number of bytes to write – Example outFile.write( reinterpret_cast ( &number ), sizeof( number ) );

 2006 Pearson Education, Inc. All rights reserved Creating a Random-Access File (Cont.) Operator reinterpret_cast – Casts a pointer of one type to an unrelated type – Also converts between pointer and integer types – Is performed at compile time Does not change the value of the object pointed to

 2006 Pearson Education, Inc. All rights reserved. 61 Error-Prevention Tip 17.1 It is easy to use reinterpret_cast to perform dangerous manipulations that could lead to serious execution-time errors.

 2006 Pearson Education, Inc. All rights reserved. 62 Portability Tip 17.1 Using reinterpret_cast is compiler- dependent and can cause programs to behave differently on different platforms. The reinterpret_cast operator should not be used unless absolute necessary.

 2006 Pearson Education, Inc. All rights reserved. 63 Portability Tip 17.2 A program that reads unformatted data (written by write ) must be compiled and executed on a system compatible with the program that wrote the data, because different systems may represent internal data differently.

 2006 Pearson Education, Inc. All rights reserved. 64 Outline ClientData.h (1 of 2)

 2006 Pearson Education, Inc. All rights reserved. 65 Outline ClientData.h (2 of 2) Store the first and last name in fixed-length char arrays – we cannot use string s because they do not have uniform length

 2006 Pearson Education, Inc. All rights reserved. 66 Outline ClientData.cpp (1 of 3)

 2006 Pearson Education, Inc. All rights reserved. 67 Outline ClientData.cpp (2 of 3) string member function data returns an array containing the characters of the string (not guaranteed to be null terminated) string member function size returns the length of lastNameString

 2006 Pearson Education, Inc. All rights reserved. 68 Outline ClientData.cpp (3 of 3)

 2006 Pearson Education, Inc. All rights reserved. 69 Outline Fig17_12.cpp (1 of 2)

 2006 Pearson Education, Inc. All rights reserved. 70 Outline Fig17_12.cpp (2 of 2) Open credit.dat in binary mode, which is required to write fixed-length records Write the data in blankClient to credit.dat as bytes

 2006 Pearson Education, Inc. All rights reserved Writing Data Randomly to a Random-Access File Writing data randomly – Opening for input and output in binary mode Use an fstream object Combine file-open modes ios::in, ios::out and ios::binary – Separate each open mode from the next with the bitwise inclusive OR operator ( | ) – Use function seekp to set the “put” file-position pointer to the specific position Example calculation – ( n – 1 ) * sizeof( ClientData ) Byte location for nth ClientData record – Use function write to output the data

 2006 Pearson Education, Inc. All rights reserved. 72 Outline Fig17_13.cpp (1 of 4) Create fstream outCredit to open credit.dat for input and output in binary mode

 2006 Pearson Education, Inc. All rights reserved. 73 Outline Fig17_13.cpp (2 of 4)

 2006 Pearson Education, Inc. All rights reserved. 74 Outline Fig17_13.cpp (3 of 4) Position the “ put ” file- position pointer to the desired byte location Write the ClientData record to the correct position in the file

 2006 Pearson Education, Inc. All rights reserved. 75 Outline Fig17_13.cpp (4 of 4)

 2006 Pearson Education, Inc. All rights reserved Reading from a Random-Access File Sequentially Sequentially reading a random-access file – ifstream member function read Inputs a number of bytes from the current file position in the stream into an object First argument – A char * pointing to the object in memory Second argument – A size_t specifying the number of bytes to input – Additional benefit Sequentially read-in records are sorted in order of ascending record keys – Space-time trade off: a fast sorting algorithm, but space- consuming

 2006 Pearson Education, Inc. All rights reserved. 77 Outline Fig17_14.cpp (1 of 3)

 2006 Pearson Education, Inc. All rights reserved. 78 Outline Fig17_14.cpp (2 of 3) This loop-continuation condition evaluates to false if an error occurs when reading from the file or if the end of file is reached

 2006 Pearson Education, Inc. All rights reserved. 79 Outline Fig17_14.cpp (3 of 3) Because outputLine takes an ostream reference as argument, it can be used with cout (an ostream object) or an ofstream object (derived from ostream ) to output to the screen or to a file

 2006 Pearson Education, Inc. All rights reserved. 80 Outline Fig17_15.cpp (1 of 10)

 2006 Pearson Education, Inc. All rights reserved. 81 Outline Fig17_15.cpp (2 of 10) “Or” together modes ios::in and ios::out for both reading and writing capabilities

 2006 Pearson Education, Inc. All rights reserved. 82 Outline Fig17_15.cpp (3 of 10)

 2006 Pearson Education, Inc. All rights reserved. 83 Outline Fig17_15.cpp (4 of 10) fstream object argument for inputting data from credit.dat

 2006 Pearson Education, Inc. All rights reserved. 84 Outline Fig17_15.cpp (5 of 10) Use istream member function seekg to ensure that the file-position pointer is at the beginning of the file

 2006 Pearson Education, Inc. All rights reserved. 85 Outline Fig17_15.cpp (6 of 10) Read data into object client, using istream member function read Determine whether the record contains information Use function outputLine with the cout ostream object to display the record

 2006 Pearson Education, Inc. All rights reserved. 86 Outline Fig17_15.cpp (7 of 10)

 2006 Pearson Education, Inc. All rights reserved. 87 Outline Fig17_15.cpp (8 of 10) Display an error message indicating that the account exists

 2006 Pearson Education, Inc. All rights reserved. 88 Outline Fig17_15.cpp (9 of 10) If the specified account is empty, display an error message Copy an empty record into the file to reinitialize that account

 2006 Pearson Education, Inc. All rights reserved. 89 Outline Fig17_15.cpp (10 of 10)

 2006 Pearson Education, Inc. All rights reserved Input/Output of Objects Inputting/outputting objects to disk files – Usually done by inputting/outputting the object’s data members We overloaded the stream extraction operator >> and stream insertion operator << for this Loses the object’s type information – If the program knows the object type, the program can read the correct type – If not, we would have to output a type code preceding each collection of data members representing an object A switch statement can then be used to invoke the proper overloaded function