Chapter 17 Input,Output,and Files
#
# An Overview of C++ Input and Output
#
# Streams and Buffers
An input stream needs two connections, one at end. The
file-end connection provides a source for the stream,
and the program-end connection dumps the stream outflow
into the program. Similarly, managing output.
A buffer is a block of memory used as an intermediate,
temporary storage facility for the transfer of infor-
mation from a device to a program or from a program to
a device.
# The streambuf class provides memory for a buffer.
# The ios_base class represents general properties of
a stream.
# The ios class is based on ios_base,and it includes a
pointer member to a streambuf object.
# The ostream and istream classes derive from the ios.
# The iostream class is based on the istream and ostream
and thus inherits both input and output methods.
When includes the iostream file in a program, Eight str-
eam objects are created:
+ cin object and wcin object
+ cout and wcout objects
+ cerr and wcerr : stream is unbuffered which means
that information is sent directly to screen,without
waiting for a buffer to fill or for a newline.
+ clog and wclog : corresponds to standard error str-
eam. All same with cerr, except that clog stream is
buffered.
# Redirection ( < and > )
#
# Output with cout
#
The ostream class translates the internal representa-
tion of data as binary bit paatterns to an output
stream of character bytes.
# The overloaded << Operato //called insertion operator
# Output and Pointers (page 1070)
The ostream class defines insertion operator functions
for the following pointer types:
+ const signed char *
+ const unsigned char *
+ cosnt char *
+ void *
the method use the terminating null character in the
string to determine when to stop displaying characters
* C++ matches a pointer of any other type with void *
and prints a numeric representation of the address.
If you want the address of the string, you have to
type cast it to another type:
int eggs = 12;
char * amount = "dozen";
cout << &eggs; //prints address of eggs variable
cout << amount; //print the string "dozen"
cout << (void *) amount; //prints the address of dozen string
# Output Concatenation
# The Other ostream Methods
Besides the various operator<<() functions, the
ostream class provides the put() method for dis-
playing characters and the write() method for
displaying strings.
osteram & put(char); //prototype
cout.put(‘W‘).put(‘I‘); //display W,I characters
cout.put(65); //displaying A character
cout.put(66.3); //displaying B character
basic_ostream<charT,traits>& write(const
Char_type * s,streamsize n);
the first argument to write provides the address
of the string to be displayed,and the second
argument indicates how many characters to display.
# Flushing the Output Buffer
Sending a newline character to the buffer to flushes
: flush and endl manipulators.
cout << "Hello, good-looking!" << flush;
//flush(cout) same action
cout << "Wait just a moment,please." << endl;
# Formatting with cout
By default:
+ Char value : one character wide
+ Numeric integer: just wide enough to hold
+ String: equal in width of the length of string
for floating-point types:
+ New style:
with total of 6 digits, trailing 0 aren‘t dis-
played. The number is displayed in fixed-point
notation or else in E notation, depending on the
value of the number. In particular, E notation is
used if the exponent is 6 or larger or -5 or
smalaer.
+ Old style:
are displayed with six places to the right of the
decimal,except the trailing zeros aren‘t displayed
# Changing the Number Base Used for Display
The ostream class inherits from the ios class,which
inherits from the ios_base class. By using ios_base
member functions, can control the field width and the
number of places displayed to the right of the decimal
...
note:
*****************************************************
in the new system,ios is a template class with
char and wchar_t specializations,and ios_base contains
the nontemplate features.
******************************************************
to control integers are displayed in base 10,16,8, you
can use the dec,hex,and oct manipulators. for example:
hex(cout);cout<<233;
or:
cout << hex << 12334;
the manipulators are in the std namespace.
# Adjusting Field Widths
You can use the width member function to place differ-
ently sized numbers in fields that have equal widths.
the method has these prototypes:
int width(); // returns the current setting
int width(int i);//return the previous field width
*** Caution:
The width() method affects only the next item dis-
played,and the field width revert to the default
value afetward.
The character used for padding is termed "fill
character",Right-justification is the default.
# Fill Characters
By default, cout fills unused parts of a field with
spaces.You can use the fill() member function to
change that.
cout.fill(‘*‘);
note that, unlike the field width, the new fill chara-
cter stay in effect until you change it.
# Setting Floating-point Display Precision
In the default mode, it means the total number of
digits displayed.
In the fixed and scientific modes, precision means the
number of digits displayed to the right of decimal
place. The precision default for C++ is 6.
The precision() member function do the job:
cout.precision(2);
The effect stays the same until it is reset.
# Printing Trailing Zeros and Decimal Points
The ios_base class provides a setf() (for set flag)
function. The class also defines several constants
that can be used as arguments to this function:
cout.setf(ios_base::showpoint);
//display trailing decimal points.
# More About setf()
The setf() function has two prototypes:
1, fmtflags setf(fmtfalgs);
fmtflags is a typedef name for a bitmask type
which is defined in the ios_base class. The return
value is the former setting of all the flags.
ios_base::boolalpha, iso_base::showbase
ios_base::showpoint, iso_base::uppercase
ios_base::showpos # (page 1085)
2, fmtflags setf(fmtflags, fmtflags );
The first argument is as before that contains the
desired setting.
The second argument is a value that first clears
the appropriate bits (eg, set first unset second)
cout.setf(ios_base::hex,ios_base::basefield);
######################################################
Table 17.2 Argument for setf(long, long) (page 1087)
Second Argument First Argument Meaning
ios_base::basefield ios_base::dec use base 10
ios_base::oct
ios_base::hex
ios_base::floatfield ios_base::fixed use fix-point
iso_base::scientific
ios_base::adjustfield ios_base::left use left_justi
ios_base::right fication
ios_base::internal
//left-justify sign or base
//prefix,right-justify value
#####################################################
The effects of calling setf() can be undone with
unsetf():
void unsetf( fmtflags mask);
Here mask is a bit pattern. All bits set to 1 in mask
cause the corresponding bits to be unset.
cout.set(ios_base::showpoint);
cout.unset(ios_base::showpoint);
cout.setf(ios_base::boolalpha);
cout.unsetf(ios_base::boolalpha);//display 1,0
Any combination,such as no bits set or both bits set,
results in the default mode being used.so:
cout.setf(0,ios_base::floatfield); //will default
or:
cout.unsetf(ios_base::floatfield); //default
# Standard Manipulators
Using setf() is not the most user-friendly approach to
formatting,so C++ offers several manipulators to invo-
ke setf().such as dec,hex,oct.
Table 17.3 Some Standard Manipulators
---------------------------------------
Manipulator Calls
boolalpha setf(ios_base::boolalpha)
noboolalpha unsetf(ios_base::boolalpha)
showbase setf(ios_base::showbase)
noshowbase
showpoint
noshowpoint
showpos
noshowpos
uppercase
nouppercase
internal setf(ios_base::internal,
ios_base::adjustfield)
left
right
dec
hex
oct
fixed
scientific setf(ios_base::scientific,
ios_base::floatfield)
---------------------------------------------
# The iomaip Header File
Setting some format values,such as the field width,
can be awkward using the iostream tools. To make life
easier,C++ supplies additional manipulators in the
iomanip header file providing the same services.
setprecision(),setfill(),setw //field width.
#
# input with cin
#
A typical operator function has a prototype like:
istream & operator>>(int &);
You can use the hex,dec,oct manipulators with cin
to specify that integer input is to be interpreted
as hexadecimal,octal,or decimal format.
for example:
cin >> hex >> x;
# How cin >> Views input
It reads everything from the initial non-white-space
character up to the first character that doesn‘t match
the destination type.
int evlevation;
cin >> evlevation;
Suppose you type the following characters:
-123G
then read -123 and the G will be remained in stream.
# Stream states
A cin or cout object contains a data member(inherited
from the ios_base class)that describles the stream
state. A stream state(defined as type iostate,which,in
turn,is a bitmask types) consists of the three ios_
base elements: eofbit,badbit,and failbit.Each element
is a single bit that can be 1 or 0.
I/O failures also set failbit.
The badbit is set when someundiagnosed failure may
have corrupted the stream.
When all three of these state bits are set 0,everyting
is fine.
Table 17.4 Stream State
---------------------------------------------------------
Member Description
eofbit Is set to 1 if end-of-file reached
badbit Is set to 1 if the stream may be corrupted;
for example: a file read error.
failbit Is set to 1 if an input operation failed to
read the expected characters or an output
operation failed to write the expected charac-
ters.
goodbit Just another way of saying 0;
good() Return true if the stream can be used(all bits
are cleared).
eof() Returns true if eofbit is set
bad() Returns true if badbit is set
fail() Returns true if badbit or failbit is set
rdstate() Returns the stream state.
exceptions() Returns a bit mask that identifies which
flags cause an exception to be thrown.
exception(iostate ex) Sets which states will cause
clear() to throw an exception; for example,
if ex is eofbit,then clear() will throw an
exception if eofbit is set
clear(iostate s) Set the stream state to s;the default
for s is 0(goodbit);throws a basic_ios::fail-
ure exception if rastate() & exceptions() != 0
setstate(iostate s) Calls clear(rdstate() | s).This sets
stream state bits corresponding to those bits
set in s;other stream state bits are left un-
changed.
----------------------------------------------------------
# Setting States
clear();//default 0. clear all three state bits
clear(eofbit); //set eofbit and clear badbit,failbit.
setstate() method affects only those bits that are set
in its argument.
setstate(eofbit); //badbit,failbit no change
# I/O and Exceptions
Changing the stream state invovles either clear() or
setstate(),which uses clear(). After changing the str-
eam state, the clear() method compares the current s-
tream state to the value returned by exception().If a
bit is set in the return value and the corresponding
bit is set in the current state,clear() throws an ios_
base::failure exception.This would happen,for example
,if both values had badbit set.
The default setting for exception() is goodbit--that
is,no exceptions thrown. The overloaded
exceptions(iostate)function gives you control over the
behavior:
cin.exceptions(badbit);
cin.exceptions(badbit | eofbit);
# Stream State Effects
An if or while test such as the following tests as
true only if the stream state is good(all bits cleared
) :
while (cin >> input)
If you want a program to read further input after a
stream state bit has been set,you have to reset the
stream state to good. by using clear() method:
cin.clear();
while (!isspace(cin.get())
continue;
cin >> input;
# Other istream Class Methods
The get(char &) and get(void) single-character input
The get(char *,int,char) and getline(char *,int,char)
functions by defult read entire lines rather than
single words.
# Single-Character Input (page 1103)
char c1,c2,c3;
cin.get(c1).get(c2) >> c3;
The method calls setstate(failbit),which causes cin to
test as fales:
char ch;
while (cin.get(ch))
{
//process
}
char ch;
ch = cin.get();
while(ch != ‘\n‘) { ... }
get(void) member function return int or larger,so can
not do like this:
cin.get().get() >> c3; //not valid
Upon reaching the end-of-file,cin.get(void) returns
the value EOF:
int ch;
while((ch = cin.get()) != EOF) { ... }
# Which Form of Single-Character Input to Use?
If skipping white space is convenient, should use >>
If examine every character, should use one of the
get() methods.
# String Input: getline(),get(),and ignore()
istream & get(char *,int,char);
istream & get(cahr *,int);
istream & getline(char *,int,char);
istream & getline(char *,int);
The first argument is the address of the location to
place the input string. The second argument is one
greater than the maximum number of characters to be
read. The third argument specifies a character to act
as a delimiter.
Each function reads up to the maximum characters or
until it encounters the delimiter character, which-
ever comes first. for example:
char line[50];
cin.get(line,50); // read 49 characters
The chief difference between get() and getline() is
that getline() extracts and discards the newline cha-
racter from the input stream.
ignore() member function takes two arguments: a num-
ber specifying a maximum number of characters to read
and a character that acts as a delimiter character.
For example,the following function call reads and
discards the next 255 characters or up through the
first newline character,whichever comes first:
cin.ignore(255,‘\n‘);
The prototype is :
istream & ignore(int = 1, int = EOF);
# Unexpected String Input
Two other special cases are no input and input that
meets or exceeds the maximum number of characters
specified by the function call.
If either method fails to extract any characters,the
method places a null character into the input string
and uses setstate() to set failbit.
Table 17.6 Inpput Behavior
------------------------------------------------------
Method Behavior
getline(char *,int) Sets failbit if no characters are
read(but newline counts as a cha-
racter read).
Set failbit if the maximum number
of characters are read and more
are still left in the line.
get(char *,int) Sets failbit if no characters are
read.
-------------------------------------------------------
# Other istream Methods
So far include read(),peek(),gcount(),and putback().
char gross[144];
cin.read(gross,144); //144 is number of bytes
The peek() function returns the next character from
input without extracting from the input stream.
The gcount() method returns the number of characters
read by the last unformatted extraction method.That
means characters read by a get(),getline(),ignore,or
read() method but not by the extraction operator(>>),
which formats input to fit particular data types.
cin.gcount();
The putback() function inserts a character back in the
input string.The inserted character then becomes the
first character read by the next input statement:
istream & putback(char);
#
# File input and output
#
To help handle these tasks, c++ defines several new
classes in the fstream header file, including the
ifstream class for file input and the ofstream class
for file output. C++ also defines the fstream class
for simulataneous file I/O.
# Simple File I/O
ofstream fout;
fout.open("jar.txt"); //ofstream fout("jar.txe");
fout << "Dull Data"; //put the words into the file.
ifstream fin;
fin.open("jellyjar.txt");
or:
ifstream fin("jellyjar.txt");
char ch;
fin >> ch; //read a character from the file
char buf[80];
fin >> buf; //read a word from the file
fin.getline(buf,80);
string line;
getline(fin,line); //read from a file to a string
The connections with a file are closed automatically
when the input and output stream objects expire.
Also can close a connection with a file explicitly by
using the close() method;
fout.close(); fin.close();
# Stream Checking and is_open()
if (!fin.is_open()) // open attempt failed
In the past:
if(fin.fail())
if(fin.good())
if(!fin)
# Opening Multiple Files
# Command-Line Processing
int main( int argc, char * argv[])
# File Modes
The file mode describes how a file is to be used:
read it, write to it, append it, and so on.
ifstream fin("banjo",mode1);
ofstream fout();
fout.open("harp",mode2);
The ios_base class defines an openmode type to repre-
sent the mode;like the fmtflags and iostate types,it
is a bitmask type.You can choose from several cons-
tants and their meanings.
Table 17.7 File Mode Constants (page 1122)
------------------------------------------------------
Constant Meaning
ios_base::in Open file for reading
ios_base::out Open file for writing.
ios_base::ate Seek to end-of-file upon opening file
ios_base::app Append to end-of-file.
ios_base::trunc Truncate file if it exists.
ios_base::binary Binary file.
------------------------------------------------------
for example:
ofstream fout("bagels",ios_base::out | ios_base::app);
# Binary Files
ofstream fout("planets.dat",ios_base::out |
ios_base::app | ios_base::binary);
fout.write( (char *) &pl,sizeof pl); //pl is structure
ifstream fin("planet.dat",ios_base::in |
ios_base::binary);
fin.read( (char *) &pl,sizeof pl);
If the class does have virtual methods,then a hidden
pointer to a table of pointers to virtual functions
is also COPIED.
# Random Access
To random accesses a file, the file‘s open mode:
ios_base::in | ios_base::out | ios_base::binary
seekg(): moves the input pointer to a given file
location.
seekp(): moves the output pointer to a given file
location.
basic_istream<charT,trait>& seekg(off_type,
ios_base::seekdir);
basic_ostream<charT,traits>& seekp(pos_type);
istream & seekg(streamoff,ios_base::seekdir);
istream & seekg(streampos);
The first prototype represents locating a file posi-
tion measured,in bytes,as an offset from a file loca-
tion specified by the second argument.
The second prototype represents locating a file posi-
tion measured,in bytes,from the beginning of a file.
seekdir includes the threes:
ios_base::beg ios_base::cur ios_base::end
for example:
fin.seeg(-1,ios_base::cur); //back up one byte
You can treat a streampos position as if it measures
a file location in bytes from the beginning of a file
,with the first byte being byte 0.
fin.seekg(112) //locates the 113th byte
tellg() and tellp() methods can find the position of
a file pointer for input stream and output stream
respectively.
fstream finout; // read and write streams
finout.open(file,ios::in | ios::out | ios::binary);
if(finout.is_open())
finout.seekg(0); //go to beginning
if(finout.eof())
finout.clear(); //clear eof flag, reuse file.
streampos place = rec * sizeof pl; //covert to bytes
finout.seekg(place);
finout.seekp(place);
finout.write((char *) &pl,sizeof pl) << flush;
#
# Incore Formatting
#
The iostream family supports I/O between a program
and a terminal.The fstream family uses the same in-
terface to provide I/O between a program and a file.
The C++ library also provides an sstream family,which
uses the same interface to provide I/O between a pro-
gram and a string object.
The process of reading formatted information from a
string object or of writing formated information to
a string object is termed "INCORE FORMATTING".
The sstream header file defines an ostringstream
class that is derived from the ostream class.
ostringstream outstr;
double price = 380.0;
char * ps = " for a copy of the C++ standard";
outstr.precision(2);
outstr << fixed;
outstr << "Pay only CHF " << price << ps << endl;
string mesg = outstr.str(); //return string with
formatted information
Using the str() method "freezes" the object,and can
no longer write to it.
istringstream instr(facts); //facts is a string
object and use it to initialize stream
while (instr >> n)
......
In short, the istringstream and ostringstream classes
give you the power of the istream and ostream class
methods to manage character data stored in strings.