File I/O ifstreams and ofstreams. Some istream Operations istream function Description cin >> ch; Extract next non-whitespace character from cin and store.

Slides:



Advertisements
Similar presentations
File Operations Functions Manipulating Files. Review The fstream library defines two classes: ifstream, for creating connections between programs and.
Advertisements

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.
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
計算機概論實習 Stream Stream: sequence of bytes Input: from device (keyboard, disk drive) to memory Output: from memory to device (monitor, printer,
1 Lecture 5: Input/Output (I) Introduction to Computer Science Spring 2006.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 3: Input/Output.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Chapter 3: Input/Output
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 27P. 1Winter Quarter I/O Manipulation Lecture.
Program Input and the Software Design Process ROBERT REAVES.
Using Classes Classes and Function Members. Review We’ve seen that the iostream library provides the objects cin, cout and cerr: These objects were not.
Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA
CHAPTER 3 INPUT/OUTPUT. In this chapter, you will:  Learn what a stream is and examine input and output streams  Explore how to read data from the standard.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 3: Input/Output.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 3: Input/Output.
Vectors of Vectors Representing Objects with Two Dimensions.
Controlling Function Behavior Sequence, Selection and Repetition.
File I/O ifstreams and ofstreams Sections 11.1 &
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.
Streams, Files, and Formatting Chapter Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output.
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.
TEXT FILES. CIN / COUT REVIEW  We are able to read data from the same line or multiple lines during successive calls.  Remember that the extraction.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1436 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah Alakeel.
Practice Building Classes Modeling Objects. Problem Write a program that computes the Dean’s List (full-time students whose GPA 3.0), using a student.
Files and Streams Chapter 9. C++ An Introduction to Computing, 3rd ed. 2 Objectives Use OCD to solve a problem involving files Study C++'s support for.
Chapter 3: Input/Output
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
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.
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.
Declaring fstream Objects An istream object named cin connects program and keyboard An ostream object named cout connects the program and the screen These.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
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++ 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.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
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.
CS212: Object Oriented Analysis and Design
Chapter 14: Sequential Access Files
Classes and Function Members
ifstreams and ofstreams
Functions Manipulating Files
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
Basic Input and Output Operations
solve the following problem...
Chapter 2 part #3 C++ Input / Output
Input and Output Chapter 3.
Standard Input/Output Streams
Standard Input/Output Streams
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Programming with Data Files
Today’s Lecture I/O Streams Tools for File I/O
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Chapter 3: Input/Output
Chapter 3 Input output.
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 2 part #3 C++ Input / Output
ifstreams and ofstreams
File I/O in C++ I.
Presentation transcript:

File I/O ifstreams and ofstreams

Some istream Operations istream function Description cin >> ch; Extract next non-whitespace character from cin and store it in ch. from cin and store it in ch. cin.get(ch); Tell cin, “Put your next character (whitespace or not) into ch.” (whitespace or not) into ch.” cin.good() Ask cin, “Are you in good shape?” cin.bad() Ask cin, “Is something wrong?" cin.fail() Ask cin, “Did the last operation fail?” cin.clear(); Tell cin, “Reset yourself to be good.” cin.ignore(n, ch); Tell cin, ignore the next n characters, or until ch occurs, whichever comes first. or until ch occurs, whichever comes first.

Some ostream Operations ostream function Description cout << expr Insert expr into cout. cout.put(ch); Tell cout, “Insert ch into yourself.” cout << flush Write contents of cout to screen. cout << endl Write a newline to cout and flush it. cout << fixed Display reals in fixed-point notation. cout << scientific Display reals in scientific notation. cout << showpoint Display decimal point and trailing zeros for real whole numbers. for real whole numbers. cout << noshowpoint Hide decimal point and trailing zeros for real whole numbers. for real whole numbers.

More ostream Operations ostream function Description cout << showpos Display sign for positive values. cout << noshowpos Hide sign for positive values. cout << boolalpha Display true, false as “true”, “false”. cout << noboolalpha Display true, false as 1, 0. cout << setprecision(n) Display n decimal places for reals. cout << setw(w) Display next value in field width w. cout << left Left-justify subsequent values. cout << right Right-justify subsequent values. cout << setfill(ch) Fill leading/trailing blanks with ch. Ex9.cpp

Problem Using OCD, design and implement a program that computes the average of a sequence of numbers stored in a file.

Preliminary Analysis Using #include, a program can read from the keyboard via the istream named cin, but this is of little benefit when the information we need is in a file... What we need is a way to somehow establish an istream-like connection between our program and the input file, such that we can then read from the file via that connection...

Behavior Our program should display its purpose and then display a prompt for the name of the input file, which it should then read. Our program should open a connection from itself to that input file. It should then read the numbers from the input file via the connection, and compute their sum and count. It should then close the connection, and compute and display the average of the numbers.

Objects Description Type Kind Name file name string varying inFileName connection ifstream varying fin number double varying number purpose, string constant -- prompt sum double varying sum count double varying count average double varying --

Operations Description Predefined? Library? Name display a string yes string << read a string yes string >> open connection yes fstream -- to a file read numbers yes fstream >> via connection sum, count numbers ?? -- +=, ++ loop close connection yes fstream close compute average ?? -- / display average yes iostream <<

Algorithm 0. Display purpose of program, and prompt for input file name. 1. Read name of input file from cin into inFileName. 2. Open connection named fin to file named in inFileName. 3. Initialize sum, count to zero. 4. Loop: a. Read a value from fin into number; b. If no values were left, terminate repetition. c. Add number to sum. d. Increment count. End loop. 5. Close fin. 6. If count > 0: display sum / count. Else display error message. End if.

Discussion To establish connections to an input file, the fstream library provides the ifstream class. It is easy for this to go wrong, so the connection should always be checked using the ifstream function member. It is easy for this to go wrong, so the connection should always be checked using the ifstream is_open() function member. Once an ifstream has been created as a connection to an input file, it can be read from using, like an istream. Once an ifstream has been created as a connection to an input file, it can be read from using >>, like an istream.

Discussion (Ct’d) The ifstream function member returns true if the last attempted read found no data remaining in the file. The ifstream function member eof() returns true if the last attempted read found no data remaining in the file. The fstream function member can be used to destroy the connection between a program and a file. The fstream function member close() can be used to destroy the connection between a program and a file.

Coding /* average.cpp *... */ #include // cin, cout,... #include // ifstream, ofstream,... #include // string #include // assert() using namespace std; int main() { cout << “\nTo average the numbers in an input file,” << “\n enter the name of the file: “; string inFileName; cin >> inFileName; ifstream fin(inFileName.data()); // open the connection assert(fin.is_open()); // verify it opened double number, sum = 0.0; // variables for int count = 0; // computing average

Coding (Ct’d) for (;;) // input loop { fin >> number; // read number if (fin.eof()) break; // if none were left, quit sum += number; // add it to sum count++; // bump count } // end loop fin.close(); // close fstream if (count > 0) cout << “\nThe average of the values in “ << inFileName << “ is “ << sum/count << endl; else cout << “\n*** No values found in file “ << inFileName << endl; }

Testing To test our program, we use a text editor and create easy-to-check input files: If we name this particular file test1.txt, then our program should display 25 for its average value.

Testing (Ct’d) Given input files, we can test our program: To average the numbers in an input file, enter the name of the file: test1.txt The average of the values in test1.txt is 25 We then continue testing using other input files, trying to find places where our program breaks down... Ex9-1.cpp

Notes The fstream library defines two classes: ifstream, for creating connections between programs and input files; andifstream, for creating connections between programs and input files; and ofstream, for creating connections between programs and output files.ofstream, for creating connections between programs and output files. Both ifstream and ofstream objects are created in a similar fashion.

Notes (Ct’d) If inFileName contains the name of an input file, and outFileName contains the name of an output file, then the statements ifstream fin(inFileName.data()); ofstream fout(outFileName.data()); define fin and fout as connections to them. Note that the string function member (or ) must be used to retrieve the actual characters of the file’s name. Note that the string function member data() (or c_str() ) must be used to retrieve the actual characters of the file’s name.

Notes (Ct’d) If a program tries to open an ifstream to a file that doesn’t exist, the open is said to fail. To check whether or not an fstream is open, the ifstream class provides the function member, which returns true if the open succeeded, and false if the open failed. To check whether or not an fstream is open, the ifstream class provides the is_open() function member, which returns true if the open succeeded, and false if the open failed. Whether or not a file opened correctly should always be verified using. Whether or not a file opened correctly should always be verified using is_open().

Notes (Ct’d) If a program tries to open an ofstream to a file that doesn’t exist, the open operation creates a new, empty file for output. If a program tries to open an ofstream to a file that does exist, the open operation (by default) empties that file of its contents, creating a clean file for output.

Notes (Ct’d) To open an existing file without emptying it, the value can be given as a second argument: To open an existing file without emptying it, the value ios_base::app can be given as a second argument: ofstream fout(outFileName.data(), ios_base::app); Character string literals can also be used to create ifstream and ofstream objects: ofstream ferr(“error.log”);

Notes (Ct’d) Once an ifstream (or ofstream) has been opened, it can be read from using the usual input (or output) operations: input: >>, get(), getline(),...input: >>, get(), getline(),... output: <<, put(),...output: <<, put(),... In general, anything that can be done to an istream (or ostream) can be done to an ifstream (or ofstream).

Notes (Ct’d) When the most recent input operation found no data remaining in the file, the input operation is said to fail. This can be detected using the ifstream function member (or ), which returns true if the last input operation encountered the end of the file, and returns false otherwise. This can be detected using the ifstream function member eof() (or fail() ), which returns true if the last input operation encountered the end of the file, and returns false otherwise.

Notes (Ct’d) The function member provides a convenient way to build input loops that employ no redundant code: The eof() function member provides a convenient way to build input loops that employ no redundant code: for (;;) { fin >> someValue; if (fin.eof()) break; //... process someValue }

Notes (Ct’d) Once we are done using an ifstream (or ofstream), it can be closed using the function member: Once we are done using an ifstream (or ofstream), it can be closed using the close() function member: fin.close(); fout.close(); Most systems limit the number of files a program can have open simultaneously, so it is a good practice to close a stream when you are finished using it. Ex9-2.cpp

Status Operations To determine the status of a stream, the libraries provide these function members: –good() // returns true iff stream is ok –bad() // returns true iff stream is not ok –fail() // returns true iff last operation failed –eof() // returns true iff last file-read failed

Change-State Operations To change the state of a stream, the libraries provide these function members: –clear() // reset status to good –setstate(b) // set state bit b (one of ios_base::goodbit,ios_base::badbit, ios_base::failbit, or ios_base::eofbit).

Read-Position Operations To manipulate the read-position within an ifstream, the libraries provide these: –tellg() // returns offset of current read-position from beginning of file –seekg(offset, base) // move read-position offset bytes from base offset bytes from base (one of ios_base::beg, ios_base::cur, or ios_base::end)

Write-Position Operations To manipulate the write-position within an ofstream, the libraries provide these: –tellp() // returns offset of current write-position from beginning of file –seekp(offset, base) // move write-position offset bytes from base offset bytes from base (one of ios_base::beg, ios_base::cur, or ios_base::end) Seek.cpp

Other Operations To look at the next character in an ifstream without advancing the read-position (i.e., without reading it), the libraries provide: –peek() // returns next char in the stream without reading it To “unread” the last char that was read, the libraries provide: –unget() // unread char most recently read

Another Operation To skip a given number of chars in the stream (or until a particular char is encountered), the libraries provide: –ignore(n, stopChar) // skip past n chars, or until stopChar is encountered

Discussion This is by no means an exhaustive list, but it does give some of the most commonly-used stream function members. See Chapter 21 of “The C++ Programming Language” by Bjarne Stroustrup (Addison- Wesley) for a complete list.

Summary C++ provides: –the ifstream for creating input connections between a program and a file. –the ofstream for creating output connections between a program and a file. Once a connection has been created, it can be manipulated using the usual I/O operations.

Summary The C++ iostream library provides a rich set of I/O functions that let a programmer: –open and close streams. –read-from/write-to streams. –get/set the state of a stream. –get the read/write position of a stream. –move the read/write position of a stream. –peek at, or unget chars from a stream. –skip over chars in a stream.