Title: Class 11 CSI2172C
1Class 11 (CSI2172C)
2Input/Output Streams in C
- A computer performs different input and output
operations such as reading data from a keyboard,
files, or peripheral device, and writing to a
screen, disk, printer, or peripheral device. - C streams are introduced to handle such
operations. - The input and output commands are not part of the
C language. In fact, they are part of the
standard output and input libraries or classes.
3Input/Output Streams in C
- A stream is a logical abstraction that represents
a data flow between -
- A source producing the data (output)
- A destination consuming the data (input)
- A stream can be seen as a buffer associated with
some mechanisms to manage the data passing
through it.
4Input/Output Streams in C
- By default, every C program can use 3 streams
- cout corresponding to the standard output
- cin corresponding to the standard input
- cerr corresponding to the standard error output
- Other streams can be created and used to handle
customized input/output operations such as
reading/writing from/to files or character
strings.
5Input/Output Streams in C
- The standard stream classes are declared in
iostream.h - ios base class for input/output streams. It
contains an object of class streambuf to manage
the input and output basic operations. - istream subclass of ios to handle input
streams. - ostream subclass of ios to handle output
streams. - iostream subclass of istream and ostream for
bi-directional streams.
6Input/Output Streams in C
7Input/Output Streams in C
- istream_withassign, ostream_withassign et
iostream_withassign are subclasses of istream,
ostream et iostream that implements the
assignment operators. - The objects cin, cout et cerr are instances of
these standard classes.
8The class ios
- ios is the base class for C streams
encapsulating the basic operations. It is not an
abstract class, but looks like it since it is not
used directly. - It provides a number of functions, variables,
and bitmaps to manage streams. - An instance of ios contains a buffer, instance
of the class streambuf. The member function
streambuf rdbuf() returns a pointer to this
buffer.
9The class ios
- ios contains a list of unary masks that return
the value of certain bit positions in a bitmap. A
bit value can be either 1 or 0. - These masks are applied to a particular state
field (bitmap) that reflects the various states
of the stream. - The state bit field cannot be accessed directly,
but can be read via the member int rdstate(void).
The following slides contain a list of bits
indicating the various states of the stream
10The class ios
- iosgoodbit If this bit is 0 and all the other
bits are also set to 0, the state in general is
good. The member function int good(void) returns
1 if all bits are set to 0, and returns 1
otherwise. - ioseofbit If this bit is 1, the end of file is
reached. The member function int eof() returns 1
in this case, 0 otherwise. - iosfailbit This bit is set to 1 when an
operation fails. The stream can still be used. - iosbadbit This bit is set to 1 when a invalid
operation is attempted. In general, the stream
can still be used but not guaranteed. - ioshardfail This bit is set to 1 when a serious
error is produced the stream should not be used.
11The class ios
- The member function int bad(void) returns 1 if
one of the two bits iosbadbit or ioshardfail
is set to 1, and returns 0 otherwise. - The member function int fail(void) returns 1 if
one of the three bits iosbadbit or iosfailbit
or ioshardfail is set to 1, and returns 0
otherwise. - The member function void clear(int i 0) allows
the modification of the streams state. For
example, applying clear to a stream fl as follows
fl.clear(iosfailbit) clear the bit iosfailbit
in fl.
12The class ios
- ios contains two additional operations
- class ios
- public
- // ...
- operator void ()
- int operator! ()
-
- The operator ! (overloaded in ios) returns 1 if
any of the bits is set to 1 (something wrong),
and returns 0 otherwise. - The operator void (also overloaded in ios)
returns 0 if any of the bits is set to 1, and
returns 0 otherwise.
//Example iostream fl if (fl) cout ltlt
Everything is fine !\n" if (!fl) cout ltlt Some
problems exist.\n"
13The class ios
- Another bit field reflects the mode of
operations. With the aid of masks, the
appropriate bit is retrieved to reflect a certain
guideline in opening, reading or writing from/to
stream. This field is mainly used with files.
Here is a list of bits with the modes they
reflect - iosin stream (file) is open in reading mode.
- iosout stream (file) is open in writing mode.
- iosapp Append input to the end of the stream
or file (not to the current position). - iosate Go the end of the stream (file) when
opening it (instead of staying at the beginning).
14The class ios
- iostrunc Delete the stream (file) if it
already exists and recreate it. - iosnocreate Do not create a stream (file) if
it does not exist an error reported in
iosfailbit if the file does not exist. - iosnoreplace If either iosate or iosapp is
not set, the stream (file) cannot be open for
input (writing). - iosbinary binary stream (file), no formatting
is applied. - For exampleÂ
- fstream fl("EXAMP.CPP", iosiniosoutiosapp)
- Open the file EXEMP.CPP in read and write mode
new data must be appended at the end.
15The class streambuf
- A buffer, or cache, is a memory area on which the
read and write operations are performed. It
handles data originated from a physical medium
(keyboard, disk), and targeted for another
(monitor, processing unit). The use of cache
optimizes the input/output process. - The class streambuf manages the input and output
operations applied to a memory cache. - Every stream will point to a given streambuf
representing a cache.
16The class ostream
- The class ostream is essential for all output
streams. It is derived from ios. - class ostream public ios
- It has a constructor ostreamostream(streambuf)
that associate a buffer to a stream, and a
destructor. -
- As in ios, the assignment operator, and the copy
constructor cannot be used since they are not
overloaded to serve these classes.
17The class ostream
- The operator ltlt is overloaded for the output
streams as shown below - ostream operatorltlt(type)
- It is in fact overloaded for all standard data
types (including unsigned char and signed char
for character string), in addition to void (for
pointer values) and also streambuf (to retrieve
characters from another buffer and writes them to
ostream). - This operator is used with the object cout which
is an instance of ostream.
18The class ostream
- cout ltlt i ltlt " and " ltlt d ltlt '\n'
- is equivalent
- cout.operatorltlt
- (i).operatorltlt
- ( and ").operatorltlt
- (d).operatorltlt('\n')
- i.e. calling four different functions.
19- When implementing a new class, we can overload
the operator ltlt to output its contents to
ostream.
class fraction int num, den public
// ... friend ostream
operatorltlt(ostream os, fraction f) return
(os ltlt f.num ltlt '/' ltlt f.den)
20The class ostream
- In addition to the insertion operator (ltlt), the
class ostream contains the following main
functions - ostream put(char c)
- inserts a character in the stream
- Example
- cout.put('\n')
- ostream write(const char , int n)
- inserts n characters in the stream
- Example
- cout.write(Good Day", 8)
21The class ostream
- An output stream feeding into a file or similar
structure has a position indicator. This
indicator marks the location of the next write
operation. It advances with every write a number
equal to the written characters. - The indicator value can be retrieved using the
member function - streampos tellp(void)
- The type streampos is identical to long.
22The class ostream
- The position indicator can be changed in two
ways - Calling the method ostream seekp(streampos n)
- where n represents the new position
relative to the - beginning of the stream. The first
position in a stream - has the value 0.
- Calling the method ostream seekp(streamoff n,
seek_dir dir). streamoff is identical to long
(similar to streampos) seek_dir is an enumerated
type specifying a reference point from which the
positioning counter starts. The seek_dir variable
(i.e dir) can have any of the following values - beg - the beginning of stream
- cur the current position of the indicator
- end the end of stream, n is negative in this
case
23 streampos old_pos fout.tellp() // keep track
of the current position fout.seekp(0, end) //
position the indicator at the end cout ltlt The
file size is " ltlt fout.tellp() ltlt "
octet(s)\n" fout.seekp(old_pos, beg) //
re-assign the indicator to its previous position
24The class ostream
- Data accumulates in a stream, until it is full or
closed, before it gets sent to the appropriate
target (device/file). - To force the stream to output its content to the
appropriate destination, the following function
is used - ostream flush(void)
- (It returns a pointer to the stream itself).
25The class istream
- The class istream is used for input streams. It
is derived from the class ios and has only one
constructor - istream istream(streambuf)
- Provides formatted and unformatted access to data
in the streambuf. - Overloads the operator gtgt
26The class istream
- In addition to the retrieval operator (gtgt), the
class istream - contains the following main methods
- Reading one character
- int get() read a character from a stream and
returns its ASCI value (or EOF if the end of file
is reached). The read character is removed from
the stream. - istream get(char c) read a character from a
stream and stores in the character c, even if it
is a space. The character gets removed. - int peek() returns the ASCI value of the next
character in a stream without removing the
character.
27The class istream
- Reading string of characters
- istream get(char ch, int n, char delim'\n')
retrieve n -1 characters from the stream and
places them at the address ch. The retrieval
process stops when hitting a delimiter given by
delim. The delimiter is by default equal to \n.
- istream getline(char ch, int n, char
delim'\n') Similar to the previous method, but
the delimiter is not stored in ch.
28The class istream
- istream read(char ch, int n)
- Retrieves a maximum of n octets from a stream
and places them at the address ch. This function
stops reading when it hits an end of file
character. The number of retrieved octets can be
obtained by the function gcount(). - int gcount()
- Returns the number of extracted after the last
read - operation.
- streampos tellg()
- returns the current position in the stream
29The class istream
- istream seekg(streampos n)
- positions the indicator at n octets from the
beginning of the stream. The type streampos
corresponds to a characters position in a
stream. - istream seekg(streamoff n, seek_dir dir)
- Positions the indicator at n octet(s) from
- the beginning of the stream dir beg
- the current position of the indicator dir cur
- the end of the stream dir end (n is
negative!) - istream flush()
- Empty the input stream
30The class iostream
- The class iostream is introduced to provide
input and output access to a stream. It is
derived from ostream and istream - class iostream public istream, public ostream
- public
- iostream(streambuf)
- virtual iostream()
- protected iostream()
-
- iostream inherits all the previously seen
functions of istream and ostream, in addition to
the two basic operators gtgt and ltlt.
31Files (opening, reading, closing)
- The file stream classes facilitate file
management.
32Files (opening, reading, closing)
-
- fstreambase Base class for the derived classes
ifstream, ofstream and fstream. It is derived
from ios and contains an object of class filebuf
(derived from streambuf). - ifstream A class allowing inputs to be received
from a file. - ofstream A class allowing outputs to be
directed to a file. - fstream A class allowing inputs and outputs to
be read from and written to a file.
33Files
-
- The three basic operations that are employed with
file streams, in addition to the set of basic
stream functions inherited from upper-classes,
are - Open() open the file
- Is_open() check if the file is open
- Close() close the file
34int main(void) // open the data file
fstream f("file_d.txt", ios_basein
ios_baseout ios_basetrunc) if
(f.is_open()) // Write the following data
f ltlt 2 ltlt " " ltlt 45.32 ltlt " " ltlt 6.37 ltlt endl
// place the file pointer at the beginning
f.seekg(0) // read the data int i double
d, e f gtgt i gtgt d gtgt e cout ltlt The data is
" ltlt i ltlt " " ltlt d ltlt " " ltlt e ltlt endl //
close the file f.close() return 0
35File opening and stream association
- The function open() opens a file and couples it
with a stream. It has the following format - void open(const char name,
- int mode,
- int protfilebufopenprot)
- name the file name to be opened
- mode mode of file opening
36Modes of File Opening
- enum open_mode of the class ios
- enum open_mode
- app,
- // adding data at the end of file
- ate,
- // positioning the indicator at the end of file
- in,
- // read access
- //(the default for ifstream).
- out,
- // write access
- //(the default for ofstream).
37Modes of File Opening
- binary,
- // binary mode
- trunc,
- // delete a file if it exists and re-create
- nocreate,
- // if the file does not exists the file opening
fails. - noreplace
- // If the file exists the opening fails only if
ate or app are set.
38include ltfstream.hgt // opening in read
mode ifstream f1 f1.open(document1.tmp") //
opening in write mode ofstream f2
f2.open(document2.tmp") // opening in
read/write mode fstream f3 f3.open(document3.t
mp", iosin iosout)
39We can also use the constructors of the file
streams to combine the stream definition and file
opening operations in one function call.
include ltfstream.hgt ifstream
f1(document1.tmp") // opening in read
mode ifstream f2(document2.tmp") // opening
in write mode ifstream f3(document3.tmp",
iosin iosout) // opening in read/write
mode
40Note The stream destructor does not close
the file. It is the programmer responsibility to
close files whenever it is not needed anymore, or
the stream is normally or abnormally destroyed.