CS240 Computer Science II - William Paterson University

Download Report

Transcript CS240 Computer Science II - William Paterson University

CS240 Computer Science II

I/O Streams

Based on Savitch’s Book Dr. E. Hu

Input/Output

• Input: can be taken from a keyboard or from a file on disk.

• Output: can be sent to the screen, a printer, or a file.

Streams

• • A

stream

if flow of data. Input

stream

flows (keyboard or input data file) into the program; output

stream

flow out of the program (screen or output data file).

Streams

are

objects

example,

cin

of certain classes. For is an object or stream that connects the keyboard (standard input device) to your program, and

cout

is an object or stream that connects your program to the screen (standard output device).

Disk files for I/O

• • Unlike screen or keyboard, disks are permanent storage devices.

• Read/write means retrieve/store.

cin

and

cout

are already defined by the system. If one wants to connect the program to a disk file, one must first declare objects of

ifstream

class for input and

ofstream

class for output. In the following example, inf and outf are arbitray object names.

ifstream inf; ofstream outf; // ifstream and ofstream

// are defined in fstream.h

// header file

The

open

member function of

ifstream

class

• The open function establishes connection between a file and the program: #include

ifstream

inf; inf.

open

(“infile.dat”); //infile.dat is the //name of the disk file int m, n; inf >> m >> n; // read two integers frominfile.dat

The

open

member function of o

fstream

class

• Similarly, … ofstream outf; outf.

open

(“outfile.dat”); outf << “m = “ << m << “n = “ << n; … Note that after the files are opened, the files are always referred to by their object names.

The

close

member function

• The close function disconnect the stream or object from the external disk file, which should always be done after the I/O processes are done.

inf.

close

( ); // no argument outf.

close

( ); // no argument

}

A simple example of file I/O

//Reads three numbers from the file infile.dat, sums the numbers, //and writes the sum to the file outfile.dat.

//(A better version of this program will be given in Display 5.2.) #include int main() { ifstream in_stream; ofstream out_stream; in_stream.open("infile.dat"); out_stream.open("outfile.dat"); int first, second, third; in_stream >> first >> second >> third; out_stream << "The sum of the first 3\n" << "numbers in infile.dat\n" << "is " << (first + second + third) << endl; in_stream.close(); out_stream.close(); return 0;

1 2 3 4

infile.dat

outfile.dat

The sum of the first 3 numbers in infile.dat

is 6

The

fail

member function of ifstream and ofstream classes

• Function call

inf.fail( )

or

outf.fail( )

returns a boolean value of either

true

(means the open operation failed) or

false

(the open operation succeeded). Its use is illustrated in the following example.

File I/O with checks on

open

//Reads three numbers from the file infile.dat, sums the numbers, //and writes the sum to the file outfile.dat. #include #include #include int main() { ifstream in_stream; ofstream out_stream; in_stream.open("infile.dat"); if (in_stream.fail()) { cout << "Input file opening failed.\n"; exit(1); }

}

File I/O with checks on

open (continued)

out_stream.open("outfile.dat"); if (out_stream.fail()) { cout << "Output file opening failed.\n"; exit(1); } int first, second, third; in_stream >> first >> second >> third; out_stream << "The sum of the first 3\n" << "numbers in infile.dat\n" << "is " << (first + second + third) << endl; in_stream.close(); out_stream.close(); return 0;

The

exit

statement

• Syntax:

exit(integer-value);

When exit function is executed, the program terminates immediately. Any integer value may be used, but by convention, 1 is used to exit that is caused by an error, and 0 is used in other cases. The exit is a function that is defined in the stdlib.h header file, so the need for #include Note that in previous examples, there were no prompt messages for the user to enter data, why?

An improved version: user is prompted to enter the external file name

//Reads three numbers from the file specified by the user, sums the //numbers, and writes the sum to another file specified by the user. #include #include #include int main( ) { char in_file_name[16], out_file_name[16]; ifstream in_stream; ofstream out_stream;

An improved version: user is prompted to enter the external file name (continued) cout << "I will sum three numbers taken from an input\n" << "file and write the sum to an output file.\n"; cout << "Enter the input file name (maximum of 15 characters):\n"; cin >> in_file_name; cout << "Enter the output file name (maximum of 15 characters):\n"; cin >> out_file_name; cout << "I will read numbers from the file " << in_file_name << " and\n" << "place the sum in the file " << out_file_name << endl; in_stream.open(in_file_name); if (in_stream.fail( )) { cout << "Input file opening failed.\n"; exit(1); }

} An improved version: user is prompted to enter the external file name (continued) out_stream.open(out_file_name); if (out_stream.fail( )) { cout << "Output file opening failed.\n"; exit(1); } int first, second, third; in_stream >> first >> second >> third; out_stream << "The sum of the first 3\n" << "numbers in " << in_file_name << endl << "is " << (first + second + third) << endl; in_stream.close( ); out_stream.close( ); cout << "End of Program.\n"; return 0;

Formatting output with stream member functions

Examples: outf.setf(ios::fixed); outf.setf(ios::showpoint); outf.precision(2); cout.width(4); cout << 7 << endl; … cout.unsetf(ios::showpos); …

Example: formatting output

//Illustrates output formatting instructions.

//Reads all the numbers in the file rawdata.dat and writes the numbers //to the screen and to the file neat.dat in a neatly formatted way.

#include #include #include #include void make_neat(ifstream& messy_file, ofstream& neat_file, int number_after_decimalpoint, int field_width); //Precondition: The streams messy_file and neat_file have been connected //to files using the function open.

//Postcondition: The numbers in the file connected to messy_file have //been written to the screen and to the file connected to the stream //neat_file. The numbers are written one per line, in fixed point notation //(i.e., not in e-notation), with number_after_decimalpoint digits after the //decimal point; each number is preceded by a plus or minus sign and //each number is in a field of width field_width. (This function does not //close the file.)

Example: formatting output (continued) int main() { ifstream fin; ofstream fout; fin.open("rawdata.dat"); if (fin.fail()) { cout << "Input file opening failed.\n"; exit(1); } fout.open("neat.dat"); if (fout.fail()) { cout << "Output file opening failed.\n"; exit(1); } make_neat(fin, fout, 5, 12); fin.close(); fout.close(); cout << "End of program.\n"; return 0; }

} Example: formatting output (continued) //Uses iostream.h, fstream.h, and iomanip.h.

void make_neat(ifstream& messy_file, ofstream& neat_file, int number_after_decimalpoint, int field_width) { neat_file.setf(ios::fixed); neat_file.setf(ios::showpoint); neat_file.setf(ios::showpos); neat_file.precision(number_after_decimalpoint); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.setf(ios::showpos); cout.precision(number_after_decimalpoint); double next; while (messy_file >> next) // returns {

true

// returns

false

if not EOF otherwise cout << setw(field_width) << next << endl; neat_file << setw(field_width) << next << endl; }

Checking for the end of a file

• The following C++ statement:

while (messy_file >> next) { … };

the “

messy_file >> next”

in the previous example, serves both as a logical expression and an expression that performs in input operation.

• Remember that operator >> is an overloaded function that returns an input steam reference (either

istream

or

ifstream

); another function is provided to convert the stream reference to a bool value.

Example: formatting output: the output (continued) • p245

Formatting flags for

setf

member function • P237-238

Manipulators

• A manipulator is a function called in a non traditional way. In turn, the manipulator function calls a member function.

• Example:

cout << “Start” << setw(4) << 10 << setw(4) << 20 << setw(6) <<30; cout << “$” << setprecision(2) << 10.3 << endl << “$” << 20.5 << endl;

Note that in order to use manipulator, one must include the following preprocessing directive:

#include

Character input with

get

member function

• Every input stream, including

cin

, has access to a

get

member function.

• Syntax:

input_stream.get(char_var);

• Examples:

char next_symbol; cin.get(next_symbol); inf.get(next_symbol);

// assuming setup properly

Character output with

put

member function

• Every output stream, including

cout

, has access to a

put

member function.

• Syntax:

output_stream.put(next_symbol);

• Example:

cout.put(next_symbol); cout.put(‘A’); outf.put(next_symbol);

The putback member function

• The example reads characters from the file connected to

fin

and write them to the file connected to the output stream

fout

. The code reads characters up to, but not include the first blank it encounters.

fin.get(next); while (next != ‘ ‘){ fout.put(next); fin.get(next); } fin.putback(next);

Example

//Program to demonstrate the functions new_line and get_input.

#include void new_line(); //Discards all the input remaining on the current input line.

//Also discards the '\n' at the end of the line.

//This version only works for input from the keyboard.

void get_int(int& number); //Postcondition: The variable number has been //given a value that the user approves of.

int main() { int n; get_int(n); cout << "Final value read in = " << n << endl << "End of demonstration.\n"; return 0; }

Example continued

//Uses iostream.h: void new_line() { char symbol; do { cin.get(symbol); } while (symbol != '\n'); } //Uses iostream.h.

void get_int(int& number) { char ans; do { cout << "Enter input number: "; cin >> number; cout << "You entered " << number << " Is that correct? (yes/no): "; cin >> ans; new_line(); } while ((ans != 'Y') && (ans != 'y')); }

Checking for the end of a file with

eof

member function

• Every input stream has access to

eof

function. It use is illustrated below:

inf.get(next); while(! inf.eof( )) { cout << next; inf.get(next); }

Example with

eof

member function

//Program to create a file called cplusad.dat which is identical to the file //cad.dat, except that all occurrences of 'C' are replaced by "C++".

//Assumes that the uppercase letter 'C' does not occur in cad.dat, except //as the name of the C programming language.

#include #include #include void add_plus_plus(ifstream& in_stream, ofstream& out_stream); //Precondition: in_stream has been connected to an input file with open.

//out_stream has been connected to an output file with open.

//Postcondition: The contents of the file connected to in_stream have been //copied into the file connected to out_stream, but with each 'C' replaced //by "C++". (The files are not closed by this function.) int main() { ifstream fin; ofstream fout; cout << "Begin editing files.\n"; fin.open("cad.dat"); if (fin.fail()){ cout << "Input file opening failed.\n"; exit(1); } }

Example with

eof

member function (continued) fout.open("cplusad.dat"); if (fout.fail()) { cout << "Output file opening failed.\n"; exit(1); } add_plus_plus(fin, fout); fin.close(); fout.close(); cout << "End of editing files.\n"; return 0; } void add_plus_plus(ifstream& in_stream, ofstream& out_stream) { char next; in_stream.get(next); while (! in_stream.eof()){ if (next == 'C') out_stream << "C++"; else out_stream << next; in_stream.get(next); } }

Inheritance and its implication in I/O

cin

and

cout

belong to

istream

and

ostream

classes which do not have

open

and

close

member functions.

ifstream

and

ofstream

are derived classes from

istream

and

ostream

with those two functions added to them.

Inheritance and its implication in I/O (continued)

void sum(ifstream & inf) { int n1, n2; inf >> n1 >> n2; cout << “Sum = “ << (n1 + n2); } … ifstream fin; sum(fin); sum(cin); // works fine.

// does not work! If we declare fin as // istream type, them both will work! // Why?

The

ios

family of classes

istream

derived class

ostream

derived class

ifstream

derived class

ofstream

derived class

An

ostream

member function

An

istream

member function

Programming assignment

• Write a program that reads text from one file and writes an edited version of the same text to another file. The edited version is identical to the unedited version except that every string of two or more consecutive blanks is replaced by a single space. Thus the text is edited to remove any extra blank characters. Your program should define a function that is called with the input and output file streams as arguments.