Chapter 9 File Streams Computing Fundamentals with C++ 3rd Edition

Slides:



Advertisements
Similar presentations
Statistical text mining using R Tom Liptrot The Christie Hospital.
Advertisements

File Input/Output. External Files Batch –Requires use of data files (save to disk) –Batch can be run during off peak use –allows things to be complete.
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.
1 Text File I/O Chapter 6 Pages File I/O in an Object-Oriented Language Compare to File I/O in C. Instantiate an ofstream object. Like opening.
9-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
1 DOS vs. UNIX files Ending lines with “\r\n” vs. “\n” Reading an entire line at a time getline() To skip white space or not cin >> ch; vs. ch = cin.get();
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 4 Programming with Data Files.
1 Programming with Data Files Chapter 4 2 Standard Input Output C++ Program Keyboard input cin Output Screen cout.
Chapter 5: Loops and Files.
1 Programming with Data Files Chapter 4. 2 Standard Input Output C++ Program Keyboard input cin Output Screen cout.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
File I/O Supplemental Material. Background In C++, files can be manipulated in the same manner we manipulate streams such as: cout and cin. Therefore,
Programming with Data Files Chapter 4. Standard Input Output C++ Program Keyboard input cin Output Screen cout.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Streams, Files. 2 Stream Stream is a sequence of bytes Input stream In input operations, the bytes are transferred from a device to the main memory Output.
Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA
Chapter 8 Data File Basics.
Files and Dictionaries CSC 161: The Art of Programming Prof. Henry Kautz 9/16/2009.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 9 I/O Streams and Data Files
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.
Define our own data types We can define a new data type by defining a new class: class Student {...}; Class is a structured data type. Can we define our.
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.
Disk Files for I/O your variable (of type ifstream) your variable (of type ofstream) disk file “myInfile.dat” disk file “myOut.dat” executing program input.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
Loops and Files. 5.1 The Increment and Decrement Operators.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
Program Input and the Software Design Process ROBERT REAVES.
Input/Output. Objectives In this chapter you will: Learn what a stream is and examine input and output streams Explore how to use the input stream functions.
1 Chapter 4 Program Input and the Software Design Process.
Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Streams and Files Problem Solving, Abstraction, and Design using.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
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.
Writing to Files and Reading From Files. Writing Data to a File Creating a new file, a.dat or.txt file #include #include // for file writing #include.
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.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Eight: Streams Slides by Evan Gallagher.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Working with Batches of Data
Chapter 14: Sequential Access Files
ifstreams and ofstreams
Chapter 8 (Part 3) Library Classes for Strings (P.405)
Copyright © 2003 Pearson Education, Inc.
Parallel Arrays Parallel array =>Two or more arrays with the same number of elements used for storing related information about a collection of data. Example:
Quiz Next Monday.
Standard Input/Output Streams
Standard Input/Output Streams
town planning I urban design I environmental assessment
Programming with Data Files
Today’s Lecture I/O Streams Tools for File I/O
Chapter 3: Input/Output
Standard Input/Output Stream
Chapter 3 Input output.
T E M P L A T E.
CS150 Introduction to Computer Science 1
File I/O in C++ I.
Formatted Input, Output & File Input, Output
CS150 Introduction to Computer Science 1
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
Reading from and Writing to Files
Programming with Data Files
ifstreams and ofstreams
T E M P L A T E.
Lecture 9 Files Handling
File I/O in C++ I.
Reading from and Writing to Files
Presentation transcript:

Chapter 9 File Streams Computing Fundamentals with C++ 3rd Edition Rick Mercer Franklin, Beedle & Associates

Goals Use ifstream objects for disk file input Use ofstream objects for disk file output Apply the indeterminate loop pattern to process data until end of file

ifstream objects ifstream objects allow input from a disk file are similar to the istream object named cin both share the same named operations both use the same operator for input << must be initialized by the programmer can be tested to determine if a disk file actually exists

ifstream objects General form to construct ifstream objects ifstream object-name ( "file-name" ) ; This associates the object name inFile with the file named "myfile.txt" in the working folder ifstream inFile("myfile.txt");

Read 3 different types #include <fstream> // for class ifstream #include <iostream> using namespace std; input.txt int main() { int n; double x; string str; ifstream inFile("input.txt"); cout << "Good? " << inFile.good() << endl; // Read 3 different types from "input.txt" Output inFile >> n; inFile >> x; inFile >> str; cout << " n: " << n << endl; cout << " x: " << x << endl; cout << "str: " << str << endl; return 0; } 100 99.9 Dakota Good? 1 n: 100 x: 99.9 str: Dakota

Getting the Path Right It is easy to initialize an ifstream object and not have it associated with an actual disk file perhaps the file does not exist perhaps the path is wrong perhaps you used \ to separate folder names Recall escape sequences look like like \n \t \ is also used to separate paths DOS and Windows (Unix uses / so this is not an issue in the Unix environment): ifstream inFile("c:\myc++\input.dat"); // NO! ifstream inFile("c:\\myc++\\input.dat"); // YES

Reading File names However, when the user enters the file name, they may use one \, or in Unix, one / string filename; cout << "Enter file name: "; cin >> filename; ifstream inFile(filename); Dialogue in DOS/Windows Enter file name: c:\temp\in.dat Dialogue in Unix Enter file name: /temp/in.dat

Indeterminate Loop with a File The end of file event can be used to terminate user input cout << "Enter numbers or end of file to quit\n"; cout << "ctrl-D (UNIX)" << endl; cout << "ctrl-Z (DOS or Windows) " << endl; string str; int n = 0; while (cin >> str) n++; cout << "You made " << n << " entries"; Enter numbers or end of file to quit ctrl-D (UNIX) ctrl-Z (DOS or Windows) a b You made 2 entries

Processing until End of File We often need to extract data from files stored on a computer disk We use ifstream objects for this kind of input The next slide shows a program that averages numbers from the file c:\input.dat

Read until end of file ifstream inFile("input.data"); input.data double number, sum = 0.0; int n = 0; while (inFile >> number) { sum += number; n++; } cout << "Average: " << (sum / n) << endl; Output 70.0 80.0 90.0 75.0 85.0 Average: 70

Mixing Numbers and Strings Use care when input has a mix of numeric and alphanumeric data. In this code, the first cin fails double hours, rate; int exemptions; string maritalStatus; string lastName, firstName; ifstream inFile("payroll.txt"); while (inFile >> hours >> rate >> maritalStatus >> exemptions >> firstName >> lastName) { This is an attempt to store a string into an int Need to swap maritalStatus with exemptions Match input order to file data or vice versa It is all too easy to get things out of order 40.0 8.88 3 S Taylor Cook 42.0 7.77 2 M Kelsey Woodman Unexpected string to int destroys the input stream

Indeterminate Loop with More Complex Disk File Input Problem: Count the words in a book Algorithm For each line in the input file: Determine the number of words in that line and add to the running sum We'll need a loop inside that loop to count the number of words in that line Each line will be processed until end of file in a loop We need the getline function (next slide)

The getline Function Use getline to read in lines of data as one string (with no 3rd argument, the default eol is '\n' istream & getline(istream & is, string & s, char sentinel = '\n') Examples string name, address; getline(cin, address); // Read from keyboard getline(inFile, name, '.'); // Read from file. // Read until end of line while( getline(infile, address) ) { // . . . 
 }

Nested loops #include <iostream> taleOf2.txt #include <fstream> #include <string> using namespace std; int main() { string line; ifstream inFile("taleOf2.txt"); int words = 0; while (getline(inFile, line)) { // Counting spaces needs one more word per line words++; for(int index = 0; index < line.length(); index ++) { if(line[index] == ' ') words++; // assume 1 space separates all words } cout << words; // 120 return 0; It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way-- in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only

ofstream objects The files storing large amounts of data are typically created by programs that send output to those files rather than the screen class ofstream class represents a disk file for output General form: ofstream object-name ( "file-name" );

ofstream #include <fstream> #include <iostream> using namespace std; int main() { ofstream outFile("output.txt"); outFile << "This does not go to the screen" << endl; cout << "This does" << endl; double x = 1.23; int n = -1; string str = "A string"; outFile << x << endl; outFile << n << endl; output.txt outFile << str << endl; outFile.close(); return 0; } This does not go to the screen 1.23 -1 A string