Chapter 9 I/O Streams and Data Files

Slides:



Advertisements
Similar presentations
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
Advertisements

© 2000 Scott S Albert Structured Programming 256 Chapter 7 Streams and File I/O.
CPS120: Introduction to Computer Science Lecture 15 B Data Files.
Chapter 10.
Chapter 5: Loops and Files.
An Introduction to Programming with C++ Fifth Edition Chapter 13 Sequential Access Files.
C++ plus. 2 Goals Some general C++ tips 3 C++ Tips is header file for a library that defines three stream objects Keyboard an istream object named cin.
Chapter 15.
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.
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
CHAPTER 6 FILE PROCESSING. 2 Introduction  The most convenient way to process involving large data sets is to store them into a file for later processing.
Program Input and the Software Design Process ROBERT REAVES.
計算機程式語言 Lecture 8-1 國立臺灣大學生物機電系 8 8 I/O File Streams and Data Files.
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
Chapter 3 Interactivity and Expressions CSC 125 Introduction to C++ programming.
Advanced Shell Programming. 2 Objectives Use techniques to ensure a script is employing the correct shell Set the default shell Configure Bash login and.
A First Book of ANSI C Fourth Edition Chapter 10 Data Files.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
Chapter 8 Data File Basics.
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
File I/O ifstreams and ofstreams Sections 11.1 &
1 CS161 Introduction to Computer Science Topic #13.
Topics 1.File Basics 2.Output Formatting 3.Passing File Stream Objects to Functions 4.More Detailed Error Testing 5.Member Functions for Reading and 6.Writing.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
Computer Programming TCP1224 Chapter 13 Sequential File Access.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
CNG 140 C Programming (Lecture set 10) Spring Chapter 10 Data Files.
1 Simple File I/O Chapter 11 Switch Statement Chapter 12.
Loops and Files. 5.1 The Increment and Decrement Operators.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
Chapter 15 Strings as Character Arrays
Chapter 9: Completing the Basics. In this chapter, you will learn about: – Exception handling – Exceptions and file checking – The string class – Character.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
Brief Version of Starting Out with C++ Chapter 1 Introduction to Computers and Programming.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Learners Support Publications Working with Files.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
File I/O. Files allow permanent storage of programs and data. ifstream and ofstream objects –For file I/O the inclusion of is required. –Objects for file.
1 Stream Input and Output Read Text, page Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Computer Programming II Lecture 9. Files Processing - We have been using the iostream standard library, which provides cin and cout methods for reading.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Eight: Streams Slides by Evan Gallagher.
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
Chapter 14: Sequential Access Files
ifstreams and ofstreams
C ++ MULTIPLE CHOICE QUESTION
Copyright © 2003 Pearson Education, Inc.
Chapter 5: Looping Starting Out with C++ Early Objects Eighth Edition
File I/O.
Lecture 5A File processing Richard Gesick.
Topics Introduction to File Input and Output
Interactive I/O Input from keyboard Must prompt user User friendly
CS150 Introduction to Computer Science 1
Topics Introduction to File Input and Output
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
A First Book of ANSI C Fourth Edition
ifstreams and ofstreams
Topics Introduction to File Input and Output
C++ for Engineers and Scientists Second Edition
Chapter 1 c++ structure C++ Input / Output
File I/O in C++ I.
Presentation transcript:

Chapter 9 I/O Streams and Data Files A First Book of C++ Chapter 9 I/O Streams and Data Files

Objectives In this chapter, you will learn about: I/O File Stream Objects and Methods Reading and Writing Text Files Random File Access File Streams as Function Arguments Common Programming Errors The iostream Class Library A First Book of C++ 4th Edition

I/O File Stream Objects and Methods To store and retrieve data outside a C++ program, you need two things: A file A file stream object A First Book of C++ 4th Edition

Files File: collection of data stored together under common name, usually on disk, USB drive, or CD/DVD C++ programs stored on disk are examples of files Stored data in program file is the code that becomes input data to C++ compiler A C++ program is not usually considered data file Data file typically refers only to files containing the data used in C++ program A First Book of C++ 4th Edition

Files External name: unique filename for file External name is how operating system knows file Contents of directory or folder are listed by external names Each computer operating system has its own specifications for external filename size Table 9.1 lists specifications for more commonly used operating systems A First Book of C++ 4th Edition

Files A First Book of C++ 4th Edition

Files Use descriptive names Avoid long filenames They take more time to type and can result in typing errors Manageable length for filename is 12 to 14 characters, with maximum of 25 characters Choose filenames that indicate type of data in file and application for which it is used Frequently, first eight characters describe data, and an extension describes application A First Book of C++ 4th Edition

Files Using DOS convention, the following are all valid computer data filenames: prices.dat records info.txt exper1.dat scores.dat math.mem A First Book of C++ 4th Edition

Files Two basic types of files: both store data using binary code Text (character-based) files: store each character using individual character code (typically ASCII or Unicode) Advantage: allows files to be displayed by word-processing program or text editor Binary-based files: store numbers in binary form and strings in ASCII or Unicode form Advantage: provides compactness A First Book of C++ 4th Edition

File Stream Objects File stream: one-way transmission path used to connect a file to a program Mode (of file stream): determines whether path will move data from file into program or from program to file Input file stream: used to transfer data from a file to a program Output file stream: sends data from a program to a file A First Book of C++ 4th Edition

File Stream Objects Direction (mode) of file stream is defined in relation to program and not file: Data that goes into program is considered input data Data sent out from program is considered output data Figure 9.1 illustrates data flow from and to file using input and output file streams A First Book of C++ 4th Edition

File Stream Objects A First Book of C++ 4th Edition

File Stream Objects Distinct file stream object must be created for each file used, regardless of file’s type For program to both read and write to file, both an input and output file stream object are required Input file stream objects are declared to be of type ifstream Output file streams are declared to be of type ofstream A First Book of C++ 4th Edition

File Stream Methods Each file stream object has access to methods defined for its respective ifstream or ofstream class, including: Opening file: connecting stream object name to external filename Determining whether a successful connection has been made Closing file: closing connection Getting next data item into program from input stream Putting new data item from program onto output stream Detecting when end of file has been reached A First Book of C++ 4th Edition

File Stream Methods open() method: Establishes physical connecting link between program and file Operating system function that is transparent to programmer Connects file’s external computer name to stream object name used internally by program Provided by the ifstream and ofstream classes File opened for input is said to be in read mode A First Book of C++ 4th Edition

File Stream Methods Example: inFile.open("prices.dat"); Connects external text file named prices.dat to internal program file stream object named inFile Accesses file using internal object name inFile Computer saves file under the external name prices.dat Calling the open() method uses the standard object notation: objectName.open() A First Book of C++ 4th Edition

File Stream Methods fail() method: returns true value if file is unsuccessfully opened, false if open succeeded Good programming practice is to check that connection is established before using file In addition to fail() method, C++ provides three other methods, listed in Table 9.2, that can be used to detect file’s status Program 9.1 illustrates statements required to open file for input, including error-checking routine to ensure that successful open was obtained A First Book of C++ 4th Edition

File Stream Methods Example of use of fail() method: ifstream inFile; // any object name can be used here inFile.open("prices.dat"); // open the file // check that the connection was opened successfully if (inFile.fail()) { cout << "\nThe file was not successfully opened" << "\n Please check that the file currently exists." << endl; exit(1); } A First Book of C++ 4th Edition

A First Book of C++ 4th Edition

File Stream Methods A First Book of C++ 4th Edition

File Stream Methods Different checking required for output files If file exists having same name as file to be opened in output mode, existing file is erased and all data lost To avoid this situation, file is first opened in input mode to see if it exists If it does, user is given choice of explicitly permitting it to be overwritten (when it is later opened in output mode) Code used to accomplish this is highlighted in Program 9.2 A First Book of C++ 4th Edition

File Stream Methods Embedding a filename in program causes problems No provision for user to enter desired filename during program execution Any changes require modification of open() method and recompile These problems can be solved by assigning filename to string variable, as shown in Programs 9.3a and 9.3b A First Book of C++ 4th Edition

A First Book of C++ 4th Edition

File Stream Methods close() method: breaks connection between file’s external name and file stream object Object can then be used for another file Good programming practice is to close files no longer needed Operating system automatically closes any open files at end of normal program execution Example: inFile.close(); closes inFile stream’s connection to its current file close() method takes no argument A First Book of C++ 4th Edition

Reading and Writing Text Files Operations similar to reading input from keyboard and writing data to display screen For writing to file, the cout object is replaced by ofstream object name declared in program Example: if outFile is declared as object of type ofstream, the following output statement is valid: outFile << descrip << ' ' << price; The filename directs output stream to file instead of standard display device Example: Program 9.4 A First Book of C++ 4th Edition

Reading and Writing Text Files Program 9.4 output: File named prices.dat is created and saved by computer as text file (the default file type) prices.dat is sequential file consisting of the following data: Mats 39.95 Bulbs 3.22 Fuses 1.08 Actual storage of characters in file depends on character codes used by computer Output file contains 36 characters (Figure 9.2) A First Book of C++ 4th Edition

Reading and Writing Text Files A First Book of C++ 4th Edition

Reading from a Text File Almost identical to reading data from standard keyboard cin object replaced by ifstream object declared in program Example: the input statement: inFile >> descrip >> price; reads next two items in file and stores them in variables descrip and price File stream name directs input to come from file stream rather than the keyboard A First Book of C++ 4th Edition

Reading from a Text File Program 9.5 illustrates how the prices.dat file created in Program 9.4 can be read Also illustrates method of detecting end-of-file (EOF) marker using good() function (see Table 9.2) Other methods that can be used for stream input are listed in Table 9.3 Each method must be preceded by stream object name A First Book of C++ 4th Edition

Reading from a Text File A First Book of C++ 4th Edition

Standard Device Files C++ supports logical and physical file objects Logical file object: stream that connects file of logically related data (data file) to a program Physical file object: stream that connects to hardware device such as keyboard or printer Standard input file: physical device assigned to program for data entry Standard output file: physical device on which output is automatically displayed A First Book of C++ 4th Edition

Other Devices The keyboard, display, error, and log streams are automatically connected to the stream objects named cin, cout, cerr, clog Requires iostream header file Other devices can be used if the name assigned by system is known Example: most personal computers assign name prn to printer connected to computer Statement outFile.open("prn") connects printer to ofstream object named outFile A First Book of C++ 4th Edition

Random File Access File access: retrieving data from file File organization: the way data is stored in a file Sequential organization: characters in file are stored in sequential manner, one after another Random access: any character in an open file can be read directly without having to read characters ahead of it A First Book of C++ 4th Edition

File Streams as Function Arguments A file stream object can be used as function argument Function’s formal parameter must be a reference (see Section 6.3) to correct stream, either as ifstream& or ofstream& Example: Program 9.8 ofstream object named outfile is opened in main() Stream object is passed to the function inOut() inOut() is used to write five lines of user-entered text to file A First Book of C++ 4th Edition

Common Programming Errors Forgetting to open a file before attempting to read from it or write to it Using file’s external name in place of internal file stream object name when accessing file Opening file for output without first checking that file with given name already exists Not checking for preexisting file ensures that file will be overwritten Not understanding that end of a file is detected only after EOF sentinel has either been read or passed over A First Book of C++ 4th Edition

Common Programming Errors Attempting to detect end of file using character variables for EOF marker Any variable used to accept EOF must be declared as an integer variable A First Book of C++ 4th Edition

Summary A data file is any collection of data stored in an external storage medium under a common name A data file is connected to file stream using fstream’s open() method This function connects file’s external name with internal object name A file can be opened in input or output mode An opened output file stream either creates a new data file or erases data in an existing opened file A First Book of C++ 4th Edition

Summary All file streams must be declared as objects of either the ifstream or ofstream classes In addition to any files opened within a function, the standard stream objects cin, cout, and cerr are automatically declared and opened when a program is run A First Book of C++ 4th Edition