Professional Documents
Culture Documents
Mca2030 SLM Unit 10
Mca2030 SLM Unit 10
Mca2030 SLM Unit 10
10.1 Introduction
In C++, I/O is done with "streams." An input stream such as cin is a source
of data that can be read into variables. An output stream such as cout is a
place where data can be sent for display, storage, or communication. A file
is a collection of data saved on a disk drive. Data in a file differs from data in
variables because a file can exist before the program is run and can persist
after the program ends. To read data from a file or to save data in a file, a
program just has to use the right type of stream. In this unit we are going to
focus on C++ I/O stream hierarchy and simple programs using these
streams.
Objectives:
After studying thus unit you should be able to:
explain C++ iostream library and its organization.
executing file I/O using streams.
Write program using I/O streams
Objects
cin Standard input stream
cout Standard output stream
cerr Standard output stream for errors
clog Standard output stream for logging
Types
fpos Stream position class template
streamoff Stream offset type
streampos Stream position type
streamsize Stream size type
Manipulators
boolalpha Alphanumerical bool values
dec Use decimal base
endl Insert newline and flush
ends Insert null character
fixed Use fixed-point notation
flush Flush stream buffer
hex Use hexadecimal base
internal Adjust field by inserting characters at an internal
position
left Adjust output to the left
noboolalpha No alphanumerical bool values
noshowbase Do not show numerical base prefixes
noshowpoint Do not show decimal point
noshowpos Do not show positive signs
noskipws Do not skip whitespaces
nounitbuf Do not force flushes after insertions
nouppercase Do not generate upper case letters
oct Use octal base
resetiosflags Reset format flags
right Adjust output to the right
scientific Use scientific notation
setbase Set basefield flag
setfill Set fill character
These two file positions are independent, and either one can point
anywhere at all in the file.
Creating Streams
Before we can use an input or output stream in a program, we must "create"
it. Statements to create streams look like variable declarations, and are
usually placed at the top of programs or function implementations along with
the variable declarations. So for example the statements
ifstream in_stream;
ofstream out_stream;
respectively create a stream called "in_stream" belonging to the class (like
type) "ifstream" (input-file-stream), and a stream called "out_stream"
belonging to the class "ofstream" (output-file-stream). However, the analogy
between streams and ordinary variables (of type "int", "char", etc.) can't be
taken too far. We cannot, for example, use simple assignment statements
with streams (e.g. we can't just write "in_stream1 = in_stream2").
Connecting and Disconnecting Streams to Files
Consider that a file named “test.txt” exists shown in figure 10.2. The
diagrammatic representation of this file is shown below:
The statement:
out_stream.close();
has a similar effect, but in addition the system will "clean up" by adding an
"end-of-file" marker at the end of the file. Thus, if no data has been output to
"Test.txt" since "out_stream" was connected to it, we change from the
situation in Figure 10.4 to figure 10.6.
You should already know what the first line is. Hence, we shall move to next
important statement.
ifstream OpenFile(“cpp-home.txt”);
ifstream means “input file stream”. In the previous program, it was ofstream,
which means “output file stream”. The previous program is to write a file,
that’s why it was “output”. But this program is to read from a file, that’s why it
is “input”. OpenFile is the object from class ifstream, which will handle the
input file stream. And in the inverted commas, is the name of the file to
open.
Notice that that there is nothing to check whether the file exists. This will be
covered in a short while.
char ch;
An explanation for this statement is redundant.
while(!OpenFile.eof())
The function eof() returns a nonzero value if the end of the file has been
reached. So, we make a while loop, that will loop until we reach the end of
the file. So, we will get through the whole file, so that we can read it.
OpenFile.get(ch);
OpenFile is the object from class ifstream. This class declares a function
called get(). So, we can use this function, as long as we have an object. The
get() function extracts a single character from the stream and returns it. In
this example, the get() function takes just one parameter – the variable
name, where to put the read character. So, after calling OpenFile.get(ch) it
will read one character from the stream OpenFile, and will put this character
into the variable ch. If you call this function for a second time, it will read the
next character, but not the same one. That’s why, we loop until we reach the
end of the file. And every time we loop, we read one character and put it into
ch.
cout << ch;
Explanation for this statement is redundant.
OpenFile.close();
As we have opened the file stream, we need to close it. Use the close()
function, to close it. Just as in the previous program.
When you compile and run this program, it should output:
Hello World, from www.cpp-home.com and Loobian!
Self Assessment Questions
5. _______________ and _______________________ are the two
position associated with opening of file
6. To connect the ifstream "in_stream" to the file "test.txt"
in_stream.open("Test.txt") statement is used [True/False]
7. Ofstream means _______________________
8. __________ function used to close the stream.
10.4 Summary
We are well acquainted with programs that use input only from the
keyboard, and output only to the screen. If we were restricted to use only
the keyboard and screen as input and output devices, it would be difficult to
handle large amounts of input data, and output data would always be lost as
soon as we turned the computer off. To avoid these problems, we can store
data in some secondary storage device, usually magnetic tapes or discs.
Data can be created by one program, stored on these devices, and then
accessed or modified by other programs when necessary. To achieve this,
the data is packaged up on the storage devices as data structures called
files.
Before we can work with files in C++, we need to become acquainted with
the notion of a stream. We can think of a stream as a channel or conduit on
which data is passed from senders to receivers. As far as the programs we
will use are concerned, streams allow travel in only one direction. Data can
be sent out from the program on an output stream, or received into the
program on an input stream. For example, at the start of a program, the
standard input stream "cin" is connected to the keyboard and the standard
output stream "cout" is connected to the screen. In fact, input and output
streams such as "cin" and "cout" are examples of (stream) objects. The
essential characteristic of stream processing is that data elements must be
sent to or received from a stream one at a time, i.e. in serial fashion.
In this chapter we have seen the entire iostream hierarchy, which has been
explained at the very beginning of this chapter. But, C++ file input and
output are typically achieved by using an object of one of the following
classes: ifstream for reading input only; ofstream for writing output only;
fstream for reading and writing from/to one file. All three classes are defined
in <fstream.h>.
This chapter has discussed comprehensively the C++ streams. Various
examples provided throughout this chapter illustrate the use of these
streams, and there is no doubt that working with streams is a relatively easy
task.
10.6 Answers
Self Assessment Questions
1. Stream
2. class templates
3. (<<) (>>)
4. True
5. Current reading and writing position.
6. True
7. output of stream
8. Close()
Terminal Questions
1. A stream is an abstraction that represents a device on which input and
output operations are performed. For more details refer section 10.2
2. Classes, objects and types are the major division under elements of
iostream library. For more details refer section 10.2
3. In C++, the file stream classes are designed with the idea that a file
should simply be viewed as a stream or array of uninterpreted bytes. For
more details refer section 10.3
4. There are several ways to read a file and display the content on the
screen. For more details refer section 10.3.