Console Stream Class Hierarchy Managing Console I/O Operations
Console Stream Class Hierarchy Managing Console I/O Operations
hierarchy
- Managing console I/O
operations
- File stream class hierarchy
- File Handling operations
Introduction
C++ provides a new technique for handling I/O operations through a mechanism known as streams.
• C++ provides several pre-defined streams that are automatically opened when the program begins its
execution. These are cin and cout.
• cin represents input stream connected to the standard input device (usually the keyboard) and cout
represents output stream connected to the standard output device (usually the screen or VDU)
• Here keyboard and screen are the default options, else redirection is possible to some other devices or
files as per requirement.
Console Stream Class Hierarchy
• C++ I/O system contains a hierarchy of classes that are used to define various kinds of stream classes
to deal with both the console and disk files.
• These classes are called stream classes.
Stream Class Hierarchy
ios is the super class for istream (input stream) and ostream (output stream) which are, in turn, base
classes for iostream (I/O stream).
The class ios is declared as the virtual base class so that only one copy of its members is inherited by
the iostream.
ios provides the basic support for formatted and unformatted I/O operations.
The class istream provides the facilities for formatted and unformatted input while the class ostream
provides the facilities for formatted output.
The class iostream provides the facilities for handling both input and output streams.
The objects cin and cout are used for input and output of different types of data.
This has been made possible by overloading the operators >> and << to recognize all the basic
C++ types.
The >> operator is overloaded in the istream class and << is overloaded in the ostream class.
get(char *) and get(void) prototypes to fetch a character including the blank space, tab and the newline
character.
The get(char *) version assigns the input character to its argument and the get(void) version returns the input
character.
Since these functions are members of the I/O stream classes and must be invoked using an appropriate
object.
Example for get(char *) function
char ch;
ch = cin.get();
while(ch != ‘\n’)
{
cout<<ch;
ch = cin.get();
}
Here the value returned by the function get() is assigned to the variable ch.
Example for put() function
The function put(), a member of ostream class, can be used to output a line of text char by
char. For instance,
cout.put(‘w’);
cout.put(ch);
cout.put(66); // Displays the char B.
Example:
char ch;
cin.get(ch);
while(ch != ‘\n’)
{
cout.put(ch);
cin.get(ch);
}
File Handling – Introduction
Many real-life problems handle large volumes of data and in such situations we need to use some devices
such as floppy disk/ hard disk to store the data.
Programs can be designed to perform read and write operations on these files.
A program typically involves either or both of the following kinds of data communication:
They represent as a sequence of bytes and deals with the flow of data.
Every stream is associated with a class having member functions and operations for a particular kind of
data flow.
All designed into fstream.h and hence needs to be included in all file handling programs.
File Input/Output Streams
File Input/Output Streams
The I/O system of C++ handles file operations which are very much similar to the console I/O
operations.
It uses file streams as an interface between the programs and the files.
The stream that supplies data to the program is known as input stream and the one that receives
data from the program is known as output stream.
In other words, the input stream extracts (reads) data from the file and the output stream inserts
(writes) data to the file.
Classes for File Stream Operations
The C++ I/O system contains a set of classes that define the file handling methods.
These classes are derived from fstreambase and from the corresponding iostream class.
These classes (designed to manage the disk files) are declared in fstream and therefore, must be
included in any program that uses files.
Stream Classes for File Operations
File Stream Classes
Opening and Closing a File
We need to consider the following things about the file
Suitable Name of the file
Purpose
Opening method
For opening a file, we must first create a file stream and then link it to the filename.
A file stream can de defined using istream, ofstream or fstream classes that are defined in the
fstream header file.
This is used when we
use only one file in
A file can be opened in two ways the stream
1. Using the constructor function of the class
This is used when
2. Using the member function, open() of the class we use multiple
files using one
stream
Opening files using Constructor
It involves the following steps:-
1. Create a file stream object to manage the stream using appropriate class. For instance, the class
ofstream is used to create the output stream and the class ifstream to create the input stream.
2. Initialize the file object with the desired filename.
Example
ofstream outfile(“Result.txt”);
PROGRAM
#include<iostream> char str1[20],str2[20];
#include<fstream> int x;
using namespace std;
ifstream inf("Check.txt");
int main()
inf>>str1;
{
inf>>x;
char name[20];
inf>>str2;
int rollno;
inf.close();
char city[20];
cout<<" Enter name, rollno and city"<<endl;
cout<<" The name is "<<str1<<endl;
file_stream_class stream_object;
stream_object.open(“ filename”);
Example 1
ofstream outf;
outf.open(“Result.txt”);
Example 2
ifstream inf;
inf.open(“Result1.txt”);
……………
…………..
inf.close();
inf.open(“Result2.txt”);
…………………..
…………………..
inf.close();
PROGRAM
char str[50];
while(inf)
int main()
{
{
inf.getline(str,50);
ofstream outf;
cout<<str<<endl;
outf.open("Country.txt");
}
outf<<"India"<<"\n";
inf.close();
outf<<"Mali"<<"\n";
inf.open("Capital.txt");
outf<<"Somalia"<<"\n";
cout<<"The contents of capital file are "<<endl;
outf<<"Bhutan"<<"\n";
while(inf)
outf.close();
{
outf.open("Capital.txt");
inf.getline(str,50);
outf<<"New Delhi"<<"\n";
cout<<str<<endl;
outf<<"Bamako"<<"\n";
}
outf<<"Mogadishu"<<"\n";
inf.close();
outf<<"Thimphu"<<"\n";
}
outf.close();
ifstream inf;
inf.open("Country.txt");
cout<<"The contents of country file are"<<endl;
PROGRAM TO READ FROM TWO FILES
SIMULTANEOUSLY. if(inf2.eof()!=0)
#include<iostream> {
#include<fstream> cout<<" Exit from capital file"<<endl;
#include<stdlib.h> exit(1);
using namespace std; }
int main()
{ inf1.getline(str,50);
ifstream inf1, inf2; cout<<"The capital of "<<str<<endl;
inf1.open("Country.txt"); inf2.getline(str,50);
inf2.open("Capital.txt"); cout<<str<<endl;
int i; }
char str[50]; inf1.close();
for(i=1;i<=10;i++) inf2.close();
{ return 0;
if(inf1.eof()!=0) }
{
cout<<" Exit from country file"<<endl;
exit(1);
}
Detecting End of File
Detection of end-of-file condition is necessary for preventing any further attempt to read data from file.
This can be done using two ways-
while(fin)
Where fin is an object of ifstream class and it return zero when end of file is reached and non zero
otherwise.
Both ios::app and ios::ate take us to the end of file when it is opened. The difference is that ios::app can
add data to the end of file only whereas ios::ate can add data or modify the existing data anywhere in the
file.
The fstream does not provide any mode by default, therefor mode must be provided explicitly by the user.
• When we open as file in write only mode, the existing contents are deleted and the output pointer
is set to the start of the file.
• When we open the file in append mode, the output pointer will be set to the end of file so that data
can be added to the existing file data.
Functions for manipulation of file pointers
The get() function reads a single character from the input stream.
The put() functions writes a single character to the output stream
Program for get() and put() function
#include<iostream> file.seekg(0);
#include<fstream> while(file)
#include<string.h> {
int main() file.get(ch);
{ cout<<ch;
char str[50],ch; }
cout<<" Enter a string"<<endl; file.close();
cin.getline(str,50); return 0;
int len = strlen(str); }
fstream file;
file.open("Sample.txt",ios::in|ios::out);
for(int i=0;i<len;i++)
{
file.put(str[i]); //writing single character at time
}
Read() and write() function
The first argument is the address of the variable V, and that must be type cast to char *( i.e pointer to
character type)
The second argument is the length of that variable in bytes.
Program for read() and write() function
#include<iostream> int main()
#include<fstream> {
#include<string.h> student obj;
using namespace std; obj.getdata();
class student ofstream outf;
{ outf.open("Sample1.dat");
int rollno; outf.write((char *)&obj, sizeof(obj)); // Writing into file
char name[20],city[30]; outf.close();
public:
void getdata() ifstream inf;
{ inf.open("Sample1.dat");
cout<<" Enter name, city and rollno"<<endl; student obj1;
cin>>name>>city>>rollno; inf.read((char *)&obj1, sizeof(obj1)); //reading from file
} obj1.display();
void display() inf.close();
{
cout<<"The name is "<<name<<endl; return 0;
cout<<"The city is "<<city<<endl; }
cout<<"The rollno is "<<rollno<<endl;
}
};
Command line arguments
Command line arguments are specified in the main() function as follows:
[NOTE: “result” will be the name of the program and in order to execute the program from
command prompt, user should compile the program first.]
Program for Command line arguments
ifstream inf;
#include<iostream>
inf.open(argv[1]);
#include<fstream>
cout<<"The contents of even file are "<<endl;
using namespace std;
while(inf)
int main(int argc, char *argv[])
{
{
inf.get(ch);
int arr[ ]={11,22,33,44,55,66,77,88,99};
cout<<ch;
char ch;
}
ofstream outf1,outf2;
inf.close();
outf1.open(argv[1]);
inf.open(argv[2]);
outf2.open(argv[2]);
cout<<"\nThe contents of odd file are "<<endl;
for(int i=0;i<8;i++)
while(inf)
{
{
if(arr[i]%2==0)
inf.get(ch);
outf1<<arr[i]<<"\t";
cout<<ch;
else
}
outf2<<arr[i]<<"\t";
inf.close();
}
return 0;
outf1.close();
}
outf2.close();