Vous êtes sur la page 1sur 9

 What is Stream IO(input/output)

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.

To perform input and output, a C++ program:

1. Construct a stream object.


2. Connect (Associate) the stream object to an actual IO device (e.g., keyboard, console,
file, network, another program).
3. Perform input/output operations on the stream, via the functions defined in the stream's
pubic interface in a device independent manner. Some functions convert the data between
the external format and internal format (formatted IO); while other does not (unformatted
or binary IO).
4. Disconnect (Dissociate) the stream to the actual IO device (e.g., close the file).
5. Free the stream object.

 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.

I/O Library Header Files

<iostream> (Header File & Function and Description)

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++";

cout << "Value of str is : " << str << endl;

getche();
}
When the above code is compiled and executed, it produces the following result −

Value of str is : Hello C++

The Standard Input Stream (cin)


The predefined object cin is an instance of istream class. The cin object is said to be
attached to the standard input device, which usually is the keyboard. The cin is used in
conjunction with the stream extraction operator, which is written as >> which are two
greater than signs as shown in the following example:
#include <iostream>
#include <conio.h>
Void main()
{
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;

}
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 −

Please enter your name: cplusplus


Your name is: cplusplus

 Header Files in C++


Header files contain definitions of Functions and Variables, which is imported or used into any
C++ program by using the pre-processor #include statement. Header file have an extension ".h"
which contains C++ function declaration and macro definition.

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++.

Types of Header Files in C++

 System header files: It is comes with compiler.


 User header files: It is written by programmer.
Why need of header files

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>

See another simple example why use header files

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.

Intro to File Input/Output in C++

 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:

% a.out < inputfile

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:

% a.out > outputfile

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.

Of course, the 2 types of redirection can be used at the same time...

% a.out < inputfile > outputfile

 C++ File I/O


While redirection is very useful, it is really part of the operating system (not C++). In fact, C++
has a general mechanism for reading and writing files, which is more flexible than redirection
alone.

iostream.h and fstream.h

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.:

ifstream inFile; // object for reading from a file


ofstream outFile; // object for writing to a file

Functions

Reading from or writing to a file in C++ requires 3 basic steps:

1. Open the file.


2. Do all the reading or writing.
3. Close the file.
Opening a File

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.

void open(const char *filename, ios::openmode mode);

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.

Sr.No Mode Flag & Description


ios::app
1
Append mode. All output to that file to be appended to the end.
ios::ate
2
Open a file for output and move the read/write control to the end of the file.
ios::in
3
Open a file for reading.
ios::out
4
Open a file for writing.
ios::trunc
5
If the file already exists, its contents will be truncated before opening the file.

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.

Reading from a File

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.

Read and Write Example

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];

// open a file in write mode.


ofstream outfile;
outfile.open("afile.dat");

cout << "Writing to the file" << endl;


cout << "Enter your name: ";
cin.getline(data, 100);

// write inputted data into the file.


outfile << data << endl;

cout << "Enter your age: ";


cin >> data;
cin.ignore();

// again write inputted data into the file.


outfile << data << endl;

// close the opened file.


outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("afile.dat");

cout << "Reading from the file" << endl;


infile >> data;

// write the data at the screen.


cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;

// close the opened file.


infile.close();

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.

Vous aimerez peut-être aussi