file i/o ifstreams and ofstreams. some istream operations istream function description cin >>...

32
File I/O File I/O ifstreams and ofstreams ifstreams and ofstreams

Upload: natalie-morgan

Post on 03-Jan-2016

224 views

Category:

Documents


3 download

TRANSCRIPT

File I/OFile I/O

ifstreams and ofstreamsifstreams and ofstreams

Some istream OperationsSome istream Operationsistream function Description

cin >> cin >> chch; Extract next non-whitespace character ; Extract next non-whitespace character

from cin and store it in from cin and store it in chch..

cin.get(cin.get(chch); Tell cin, “Put your next character); Tell cin, “Put your next character (whitespace or not) into (whitespace or not) into chch.”.”

cin.good() Ask cin, “Are you in good shape?”cin.good() Ask cin, “Are you in good shape?”

cin.bad() Ask cin, “Is something wrong?"cin.bad() Ask cin, “Is something wrong?"

cin.fail() Ask cin, “Did the last operation fail?”cin.fail() Ask cin, “Did the last operation fail?”

cin.clear(); Tell cin, “Reset yourself to be good.”cin.clear(); Tell cin, “Reset yourself to be good.”

cin.ignore(cin.ignore(nn, , chch); Tell cin, ignore the next ); Tell cin, ignore the next nn characters, characters, or until or until chch occurs, whichever comes first. occurs, whichever comes first.

Some ostream OperationsSome ostream Operationsostream function Description

cout cout <<<< exprexpr Insert Insert exprexpr into cout. into cout.

cout.put(cout.put(chch); Tell c); Tell coutout, “Insert , “Insert chch into yourself.” into yourself.”

cout << flush Write contents of cout to screen.cout << flush Write contents of cout to screen.

cout << endl Write a newline to cout and flush it.cout << endl Write a newline to cout and flush it.

cout << fixed Display reals in fixed-point notation.cout << fixed Display reals in fixed-point notation.

cout << scientific Display reals in scientific notation.cout << scientific Display reals in scientific notation.

cout << showpoint Display decimal point and trailing zeroscout << showpoint Display decimal point and trailing zeros for real whole numbers.for real whole numbers.

cout << noshowpoint Hide decimal point and trailing zeroscout << noshowpoint Hide decimal point and trailing zeros for real whole numbers.for real whole numbers.

More ostream OperationsMore ostream Operationsostream function Description

cout << showpos Display sign for positive values.cout << showpos Display sign for positive values.

cout << noshowpos Hide sign for positive values.cout << noshowpos Hide sign for positive values.

cout << boolalpha Display true, false as “true”, “false”.cout << boolalpha Display true, false as “true”, “false”.

cout << noboolalpha Display true, false as 1, 0.cout << noboolalpha Display true, false as 1, 0.

cout << setprecision(cout << setprecision(nn) Display ) Display nn decimal places for reals. decimal places for reals.

cout << setw(cout << setw(ww) Display next value in field width ) Display next value in field width ww..

cout << left Left-justify subsequent values.cout << left Left-justify subsequent values.

cout << right Right-justify subsequent values.cout << right Right-justify subsequent values.

cout << setfill(cout << setfill(chch) Fill leading/trailing blanks with ) Fill leading/trailing blanks with ch.ch.

•Ex9.cpp

ProblemProblem

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

Preliminary AnalysisPreliminary Analysis

Using #include <iostream>, a program Using #include <iostream>, a program can read from the keyboard via the can read from the keyboard via the istream named cin, but this is of little istream named cin, but this is of little benefit when the information we need is benefit when the information we need is in a file...in a file...

What we need is a way to somehow What we need is a way to somehow establish an istream-like connection establish an istream-like connection between our program and the input file, between our program and the input file, such that we can then read from the file such that we can then read from the file via that connection...via that connection...

BehaviorBehavior

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

ObjectsObjects

Description Type Kind NameDescription Type Kind Name

file name string varying inFileNameconnection ifstream varying finnumber double varying number

purpose, string constant -- prompt

sum double varying sumcount double varying countaverage double varying --

OperationsOperations

Description Predefined? Library? NameDescription 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 closecompute average ?? -- /

display average yes iostream <<

AlgorithmAlgorithm0. Display purpose of program, and prompt for input file 0. Display purpose of program, and prompt for input file

name.name.1. Read name of input file from 1. Read name of input file from cincin into into inFileNameinFileName..2. Open connection named 2. Open connection named finfin to file named in to file named in inFileNameinFileName..3. Initialize 3. Initialize sumsum, , countcount to zero. to zero.4. Loop:4. Loop:

a. Read a value from a. Read a value from finfin into into numbernumber;;b. If no values were left, terminate repetition.b. If no values were left, terminate repetition.c. Add c. Add numbernumber to to sumsum..d. Increment d. Increment countcount..End loop.End loop.

5. Close 5. Close finfin..6. If count > 0: display 6. If count > 0: display sum / countsum / count..

Else display error message.Else display error message.End if.End if.

DiscussionDiscussion

To establish connections to an input file, the To establish connections to an input file, the fstream library provides the fstream library provides the ifstreamifstream class. class.

It is easy for this to go wrong, so the It is easy for this to go wrong, so the connection should always be checked connection should always be checked using the ifstream using the ifstream is_open() function function member.member.

Once an ifstream has been created as a Once an ifstream has been created as a connection to an input file, it can be read connection to an input file, it can be read from using from using >>, like an istream., like an istream.

Discussion (Discussion (Ct’dCt’d))

The ifstream function member The ifstream function member eof() returns true if the last attempted read returns true if the last attempted read found no data remaining in the file.found no data remaining in the file.

The fstream function member The fstream function member close() can be used to destroy the connection can be used to destroy the connection between a program and a file.between a program and a file.

CodingCoding/* average.cpp * ... */#include <iostream> // cin, cout, ...#include <fstream> // ifstream, ofstream, ...#include <string> // string#include <cassert> // 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 (Coding (Ct’dCt’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;}

TestingTesting

To test our program, we use a text To test our program, we use a text editor and create easy-to-check editor and create easy-to-check input files:input files:

10 203040

If we name this particular file If we name this particular file test1.txttest1.txt, then our program should , then our program should display 25 for its average value.display 25 for its average value.

Testing (Testing (Ct’dCt’d))

Given input files, we can test our Given input files, we can test our program: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 We then continue testing using other input files, trying to find places input files, trying to find places where our program breaks down...where our program breaks down...

•Ex9-1.cpp

NotesNotes

The fstream library defines two classes:The fstream library defines two classes:

• ifstreamifstream, for creating connections , for creating connections between programs and input files; andbetween programs and input files; and

• ofstreamofstream, for creating connections , for creating connections between programs and output files.between programs and output files.

Both ifstream and ofstream objects are Both ifstream and ofstream objects are created in a similar fashion.created in a similar fashion.

Notes (Notes (Ct’dCt’d))

If If inFileNameinFileName contains the name of an input contains the name of an input file, and file, and outFileNameoutFileName contains the name of contains the name of an output file, then the statementsan output file, then the statements

ifstream fin(inFileName.data());

ofstream fout(outFileName.data());

define fin and fout as connections to them.define fin and fout as connections to them.

Note that the string function member Note that the string function member data() (or (or c_str()) must be used to retrieve the ) must be used to retrieve the actual characters of the file’s name.actual characters of the file’s name.

Notes (Notes (Ct’dCt’d))

If a program tries to open an ifstream to a If a program tries to open an ifstream to a file that doesn’t exist, the open is said to file that doesn’t exist, the open is said to failfail. .

To check whether or not an fstream is open, To check whether or not an fstream is open, the ifstream class provides the the ifstream class provides the is_open() function member, which returns true if the function member, which returns true if the open succeeded, and false if the open open succeeded, and false if the open failed.failed.

Whether or not a file opened correctly should Whether or not a file opened correctly should alwaysalways be verified using be verified using is_open()..

Notes (Notes (Ct’dCt’d))

If a program tries to open an ofstream to If a program tries to open an ofstream to a file that doesn’t exist, the open a file that doesn’t exist, the open operation creates a new, empty file for operation creates a new, empty file for output.output.

If a program tries to open an ofstream to If a program tries to open an ofstream to a file that does exist, the open a file that does exist, the open operation (by default) empties operation (by default) empties that file of its contents, creating a that file of its contents, creating a clean file for output.clean file for output.

Notes (Notes (Ct’dCt’d))

To open an existing file without emptying To open an existing file without emptying it, the value it, the value ios_base::app can be can be given as a second argument:given as a second argument:

ofstream fout(outFileName.data(), ios_base::app);

Character string literals can also be used Character string literals can also be used to create ifstream and ofstream objects:to create ifstream and ofstream objects:

ofstream ferr(“error.log”);

Notes (Notes (Ct’dCt’d))

Once an ifstream (or ofstream) has been Once an ifstream (or ofstream) has been opened, it can be read from using the opened, it can be read from using the usual input (or output) operations:usual input (or output) operations:

• input: >>, get(), getline(), ...input: >>, get(), getline(), ...

• output: <<, put(), ...output: <<, put(), ...

In general, anything that can be done to an In general, anything that can be done to an istream (or ostream) can be done to an istream (or ostream) can be done to an ifstream (or ofstream).ifstream (or ofstream).

Notes (Notes (Ct’dCt’d))

When the most recent input operation When the most recent input operation found no data remaining in the file, the found no data remaining in the file, the input operation is said to input operation is said to failfail..

This can be detected using the ifstream This can be detected using the ifstream function member function member eof() (or (or fail()), ), which returns true if the last input which returns true if the last input operation encountered the end of the file, operation encountered the end of the file, and returns false otherwise.and returns false otherwise.

Notes (Notes (Ct’dCt’d))

The The eof() function member provides a function member provides a convenient way to build input loops that convenient way to build input loops that employ no redundant code:employ no redundant code:

for (;;){ fin >> someValue;

if (fin.eof()) break;

// ... process someValue}

Notes (Notes (Ct’dCt’d))

Once we are done using an ifstream Once we are done using an ifstream (or ofstream), it can be closed using (or ofstream), it can be closed using the the close() function member: function member:

fin.close();fout.close();

Most systems limit the number of files a Most systems limit the number of files a program can have open simultaneously, program can have open simultaneously, so it is a good practice to close a so it is a good practice to close a stream when you are finished using it.stream when you are finished using it.

•Ex9-2.cpp

Status OperationsStatus Operations

To determine the status of a stream, the To determine the status of a stream, the libraries provide these function libraries provide these function members:members:– good() // returns true iff stream is okgood() // returns true iff stream is ok

– bad() // returns true iff stream is not okbad() // returns true iff stream is not ok

– fail() // returns true iff last operation fail() // returns true iff last operation failedfailed

– eof() // returns true iff last file-read eof() // returns true iff last file-read failedfailed

Change-State OperationsChange-State Operations

To change the state of a stream, the To change the state of a stream, the libraries provide these function members:libraries provide these function members:– clear() // reset status to goodclear() // reset status to good

– setstate(b) // set state bit b (one ofsetstate(b) // set state bit b (one of

ios_base::goodbit,ios_base::goodbit,ios_base::badbit,ios_base::badbit,ios_base::failbit, ios_base::failbit,

ororios_base::eofbit).ios_base::eofbit).

Read-Position OperationsRead-Position Operations

To manipulate the read-position within an To manipulate the read-position within an ifstream, the libraries provide these:ifstream, the libraries provide these:– tellg() // returns offset of currenttellg() // returns offset of current

read-position fromread-position frombeginning of filebeginning of file

– seekg(seekg(offsetoffset, , basebase) // move read-position) // move read-position offsetoffset bytes from bytes from basebase (one of ios_base::beg,(one of ios_base::beg,ios_base::cur, orios_base::cur, orios_base::end)ios_base::end)

Write-Position OperationsWrite-Position Operations

To manipulate the write-position within an To manipulate the write-position within an ofstream, the libraries provide these:ofstream, the libraries provide these:– tellp() // returns offset of currenttellp() // returns offset of current

write-position fromwrite-position frombeginning of filebeginning of file

– seekp(seekp(offsetoffset, , basebase) // move write-position) // move write-position offsetoffset bytes from bytes from basebase (one of ios_base::beg,(one of ios_base::beg,ios_base::cur, orios_base::cur, orios_base::end)ios_base::end)

•Seek.cpp

DiscussionDiscussion

This is by no means an exhaustive list, This is by no means an exhaustive list, but it does give some of the most but it does give some of the most commonly-used stream function commonly-used stream function members.members.

See Chapter 21 of “The C++ See Chapter 21 of “The C++ Programming Language” by Bjarne Programming Language” by Bjarne Stroustrup (Addison-Wesley) for a Stroustrup (Addison-Wesley) for a complete list.complete list.

SummarySummary

C++ provides:C++ provides:– the the ifstreamifstream for creating input connections between a for creating input connections between a

program and a file.program and a file.

– the the ofstreamofstream for creating output connections between a for creating output connections between a program and a file.program and a file.

Once a connection has been created, it can be Once a connection has been created, it can be manipulated using the usual I/O operations.manipulated using the usual I/O operations.

SummarySummary

The C++ iostream library provides a rich set The C++ iostream library provides a rich set of I/O functions that let a programmer:of I/O functions that let a programmer:– open and close streams.open and close streams.

– read-from/write-to streams.read-from/write-to streams.

– get/set the state of a stream.get/set the state of a stream.

– get the read/write position of a stream.get the read/write position of a stream.

– move the read/write position of a stream.move the read/write position of a stream.

– peek at, or unget chars from a stream.peek at, or unget chars from a stream.

– skip over chars in a stream.skip over chars in a stream.