Académique Documents
Professionnel Documents
Culture Documents
1.1 Streams
C/C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs
(just like water and oil flowing through a pipe). In input operations, data bytes flow from an
input source (such as keyboard, file, network or another program) into the program. In output
operations, data bytes flow from the program to an output sink (such as console, file, network or
another program). Streams acts as an intermediaries between the programs and the actual IO
devices, in such the way that frees the programmers from handling the actual devices, so as to
archive device independent IO operations.
C++ provides both the formatted and unformatted IO functions. In formatted or high-level IO,
bytes are grouped and converted to types such as int, double, string or user-defined types. In
unformatted or low-level IO, bytes are treated as raw bytes and unconverted. Formatted IO
operations are supported via overloading the stream insertion (<<) and stream extraction (>>)
operators, which presents a consistent public IO interface.
What is a buffer?
A temporary storage area is called buffer. All standard input and output devices contain an input
and output buffer. In standard C/C++, streams are buffered, for example in the case of standard
input, when we press the key on keyboard, it isn’t sent to your program, rather it is buffered by
operating system till the time is allotted to that program.
A buffer flush is the transfer of computer data from a temporary storage area to the computer’s
permanent memory. For instance if we make any changes in a file, the changes we see on one
computer screen are stored temporarily in a buffer.
Usually a temporary file come into existence when we open any word document, and
automatically destroyed when we close our main file. Thus when we save our work, the changes
that we’ve made to our document since the last time we saved it are flushed from the buffer to
permanent storage on the hard disk.
IOSTREAMS
The C++ standard libraries provide an extensive set of input/output capabilities which we
will see in subsequent chapters. This chapter will discuss very basic and most common
I/O operations required for C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like
a keyboard, a disk drive, or a network connection etc. to main memory, this is called
input operation and if bytes flow from main memory to a device like a display screen, a
printer, a disk drive, or a network connection, etc., this is called output operation.
This file defines the cin, cout, cerr and clog objects, which correspond to the standard
input stream, the standard output stream, the un-buffered standard error stream and the
buffered standard error stream, respectively.
The Standard Output Stream (cout)
The predefined object cout is an instance of ostream class. The cout object is said to be
"connected to" the standard output device, which usually is the display screen. The cout is used
in conjunction with the stream insertion operator, which is written as << which are two less than
signs as shown in the following example.
#include <iostream.h>
#include <conio.h>
void main()
{
char str[] = "Hello C++";
getche();
}
When the above code is compiled and executed, it produces the following result −
}
When the above code is compiled and executed, it will prompt you to enter a name. You enter a
value and then hit enter to see the following result −
Each header file contains information (or declarations) for a particular group of functions. Like
stdio.h header file contains declarations of standard input and output functions available in C++
which is used for get the input and print the output. Similarly, the header file math.h contains
declarations of mathematical functions available in C++.
When we want to use any function in our C++ program then first we need to import their
definition from C++ library, for importing their declaration and definition we need to include
header file in program by using #include. Header file include at the top of any C++ program.
For example if we use clrscr() in C++ program, then we need to include, conio.h header file,
because in conio.h header file definition of clrscr() (for clear screen) is written in conio.h header
file.
Syntax
#include<conio.h>
Syntax
#include<iostream>
int main()
{
using namespace std;
cout << "Hello, world!" << endl;
return 0;
}
In above program print message on scree hello world! by using cout but we don't define cout
here actually already cout has been declared in a header file called iostream.
Redirection
One way to get input into a program or to display output from a program is to use standard input
and standard output, respectively. All that means is that to read in data, we use cin (or a few
other functions) and to write out data, we use cout.
When we need to take input from a file (instead of having the user type data at the keyboard) we
can use input redirection:
This allows us to use the same cin calls we use to read from the keyboard. With input
redirection, the operating system causes input to come from the file (e.g., inputfile above)
instead of the keyboard.
Similarly, there is output redirection:
that allows us to use cout as before, but that causes the output of the program to go to a file (e.g.,
outputfile above) instead of the screen.
There are types and functions in the library iostream.h that are used for standard I/O. fstream.h
includes the definitions for stream classes ifstream (for input from a file), ofstream (for output
to a file) and fstream (for input to and output from a file). Make sure you always include that
header when you use files.
Type
For files you want to read or write, you need a file stream object, e.g.:
Functions
A file must be opened before you can read from it or write to it. Either ofstream or fstream
object may be used to open a file for writing. And ifstream object is used to open a file for
reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and
ofstream objects.
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open() member function defines the mode in which the file should be opened.
You can combine two or more of these values by ORing them together. For example if you want
to open a file in write mode and want to truncate it in case that already exists, following will be
the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the allocated
memory and close all the opened files. But it is always a good practice that a programmer should
close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream,
and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the screen.
The only difference is that you use an ofstream or fstream object instead of the cout object.
You read information from a file into your program using the stream extraction operator (>>)
just as you use that operator to input information from the keyboard. The only difference is that
you use an ifstream or fstream object instead of the cin object.
Following is the C++ program which opens a file in reading and writing mode. After writing
information entered by the user to a file named afile.dat, the program reads information from the
file and outputs it onto the screen −
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
return 0;
}
When the above code is compiled and executed, it produces the following sample input and output −
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline() function to read the line
from outside and ignore() function to ignore the extra characters left by previous read statement.