Chapter 7:Stream computation for
console and file input/output.
Prepared by:[Link] Neupane
[Link],KEC Kalimati
Stream class hierarchy for console input/output:(Imp)
C++ I/O system contains a hierarchy of classes that are used to
define various streams to deal with both the console and disk files.
These classes are called stream classes. These classes are declared
in the header file iostream and hence should be included in all the
programs that communicate with the console unit. Following figure
shows the hierarchy of the stream classes used for input/output
operations with the console unit.
ios
istream streambuf ostream
iostream
istream_withassign iostream_withassign ostream_withassign
Figure:Stream classes for console Input/Output operation
Different stream classes associated with console input/output are as
follows:
i)ios(General input/output stream class):
-Contains basic facilities that are used by all other input/output
classes.
ii)streambuf:
-The streambuf class holds the characters written or read from input
devices before they are sent to actual destination.
iii)istream(input stream):
-Inherits the properties of ios
-Declares input functions such as get( ),getline( ) and read( ) as
member functions.
-Contains overloaded extraction operator (>>).
iv)ostream(output stream):
-inherits the properties of ios.
-contains output member functions put( ) and write( ).
-contains overloaded insertion operator (<<).
v)iostream(input/output stream):
-inherits the properties of istream and ostream classes.
-all of the functions and operators available with istream and
ostream classes are available in iostream class.
-cout is predefined object of ostream_withassign and cin is
predefined object of istream_withassign.
Formatted input/output with ios class member
functions and flags:(Imp)
-For the formatted input/output, C++ provides some ios class
member functions and flags. Some important member functions of
ios class that are used for formatting are:
width( ):It is used to define the width of the field to be used while
displaying the output.
Syntax:
[Link](w);
Where w is the width([Link] columns) of the field.
Example:
[Link](6);
cout<<849;
Output:
_ _ _849
Note:
This function can specify the field width for only one item and
revert back to default after printing one item.
precision( ):
-It is used to specify the number of digits to be displayed after
the decimal point while printing the floating point numbers.
-Unlike width( ),precision( ) retains the setting in effect until it
is reset.
Syntax:
[Link](d);
Example:
[Link](3);
cout<<sqrt(2)<<endl;
cout<<3.14159<<endl;
cout<<2.50032<<endl;
[Link](5);//reset the precision
cout<<3.14159;
Output:
1.414
3.142
2.5 (no trailing zeros)
3.14159
-fill( )
-It is used to specify the character to be displayed in the unused
portion of the display width.
Syntax:
[Link](ch);
Where ch represents the character which is used for filling the
unused portion.
Example:
[Link](‘*’);
[Link](10);
cout<<5250;
Output:
******5250
Note: Like precision( ),fill( ) stays in effect until we change it.
-setf( )
C++ provides other ways of output formatting like left
justified,scientific form,show positive sign,show base of displayed
number [Link] is the member function of the ios class that uses
formatting flag and bitfield as an argument for formatted output.
Syntax: [Link](arg1,arg2);
Where,arg1 is one of the formatting flags defined in ios class and it
specifies the format action required for the output and arg2 is one of the
bit fields specifying the group to which the formatting flag belongs to.
Format Required Flag(arg1) Bit-field(arg2)
Left-justified output ios::left ios::adjustfield
Right-justified output ios::right ios::adjustfield
Padding after sign (+##20) ios::internal ios::adjustfield
Scientific notation ios::scientific ios::floatfield
Fixed point notation ios::fixed ios::floatfield
Decimal base ios::dec ios::basefield
Octal base ios::oct ios::basefield
Hexadecimal base ios::hex ios::basefield
Example:
[Link](‘*’);
[Link](3);
[Link](ios::internal,ios::adjustfield);
[Link](ios::scientific,ios::floatfield);
[Link](15);
cout<<-12.34557;
Output:
-****1.235e+001
-setf( )can also be used with a single argument also.
Flag Meaning
ios:showbase Use base indicator on output
ios::showpos Print ‘+’ before positive number
ios::showpoint Show trailing decimal point and zeros
ios::uppercase Use uppercase letters for hex output
ios::skipws Skip white space on input
ios::unitbuf Flush all streams after insertion
ios::boolalpha Display ‘true’ or ‘false’ instead 1 or 0
ios::stdio Flush stdout and stderr after insertion
Example:
[Link](ios::showpoint);
[Link](ios::showpos);
[Link](3);
[Link](ios::fixed,ios::floatfield);
[Link](ios::internal,ios::adjustfield);
[Link](10);
cout<<275.5;
Output:
+ 275.500
unsetf( ):
It is used to unset the specified flag value.
Example:
[Link](ios::showpos);
Here, output will not display ‘+’ sign in displaying positive number.
Formatting with manipulators:(Imp)
The header file iomanip provides a set of functions called
manipulators which can be used to manipulate the output formats.
They provide the same features as that of the ios member functions
and flags. We can use two or more manipulators as a chain in one
statement however we cannot use ios class member functions and
flags as a chain in a program.
For example, cout<<manip1<<manip2<<item;
cout<<manip1<<manip2<<item<<manip3;
Manipulators can be categorized as non-parameterized
manipulators and parameterized [Link]-parameterized
manipulators do not take argument to control the formatting of
input/output whereas parameterized manipulators take argument for
formatting.
Following are some non parameterized manipulators:
Manipulators Effect produced
endl Gives a new line
left Sets ios::left flag of ios::adjustfield
right Sets ios::right flag of ios::adjustfield
showpoint Sets ios::showpoint flag
scientific Sets ios::scientific flag of ios::floatfield
fixed Sets ios::fixed flag of ios::floatfield
Following are some of the parameterized manipulators:
Manipulators Effect Produced
12345
setw(int n) Equivalent to ios function width( )
setprecision(int n) Equivalent to ios function precision( )
setfill(char c) Equivalent to ios function fill( )
setiosflags(flag) Equivalent to ios function setf( )
resetiosflags(flag) Equivalent to ios function unsetf( )
Note:We can jointly use manipulators and ios functions in a program.
- Example of manipulators:
cout<<setfill(‘*’)<<setw(7)<<12345;
Output:
**12345
File stream class hierarchy(Imp):
The I/O system of C++ contains a set of classes that define the
file handling methods. These includes ifstream,ofstream, and
[Link] classes are derived from fstreambase and from
the corresponding iostream class as shown in the figure. These
classes designed to manage the disk files are declared in
header file fstream and therefore we must include this file in
any program that uses files.
filebuf:
The filebuf class is used to set the file buffer to read and
write. The filebuf class is internally used by the file stream
classes for the buffer management. It contains close( ) and
open( ) as members.
fstrembase:
This class provides operations common to the file
streams(ifstream,ofstream and fstream). It serves as a base for
fstream,ifstream and ofstream class and it contains open( )
and close( ).
ifstream:
This class provides input operations. It contains open( ) with
default input mode. It inherits the function
get(),getline(),read(),seekg() and tellg() from istream class.
ofstream:
This class provides output operations. It contains open() with
default output [Link] inherits put(),seekp(),tellp(),write()
functions from ostream.
fstream:
It provides support for simultaneous input and output
operations. It inherits all the functions of istream and ostream
classes through iostream.
Opening and closing files(Imp):
A file can be opened in either of the following ways:
i)Using the constructor function of the stream class.
ii)Using the member function open( )
i)Using the constructor function of the stream class.
Example:
ifstream fin(“[Link]”);
-This statement creates an object fin of ifstream class and
after that the file [Link] is opened for reading from it
and it is attached to input stream fin.
-To read from this file
int d;
fin>>d;//Extracts integer value from file.
-To close this file we use the statement as [Link]( );
ofstream fout(“[Link]”);
-This statement creates an object fout of ofstream class and
after that the file [Link] is opened for writing and it is
attached to output stream fout.
Example:
fout<<name<<endl;//writing to file
fout<<roll;//writing to file
-To close this file we use [Link]();
ii)Opening files using open( ) function:
Apart from constructor, file can be opened explicitly by
making use of member function open( ).The function open( )
is a member of all the file stream classes ofstream,ifstream and
fstream. This mechanism is generally used when different files
are to be associated with the same object at different times.
Example:
ifstream fin;//create stream(for input)
[Link](“[Link]”);//connect stream to [Link] for reading
from this file
[Link]( );//disconnect stream from [Link]
ofstream fout;//create stream (for output)
[Link](“[Link]”);//connect stream to [Link] for
writing in to this file
[Link]( );//disconnect stream from [Link]
Note: When an input file connection is closed, the data is moved
from the input buffer to the program and when an output file
connection is closed, the data is moved from the output buffer to
the disk file.
Note:By using open function we can open multiple files for
reading or writing purpose but the constructor function of stream
class does not allow us to do so.
Q)Write a program to copy the contents of one file into another
file using the concept of object oriented programming.
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
class Text
{
char name[50];
char address[50];
char fathername[50];
public:
void input( )
{
cout<<"Enter the name address and father name:";
cin>>name>>address>>fathername;
}
void display( )
{
cout<<"Name="<<name<<endl;
cout<<"Address="<<address<<endl;
cout<<"Father's name="<<fathername<<endl;
}
};
void add_details( )
{
fstream fout;
[Link]("[Link]",ios::app|ios::binary|ios::out);
Text t;
[Link]( );
[Link]((char*)&t,sizeof(t));
[Link]( );
}
void copy_contents( )
{
fstream fout;
fstream fin;
Text t;
[Link]("[Link]",ios::in|ios::binary);
[Link]("[Link]",ios::app|ios::binary);
while([Link]((char*)&t,sizeof(t)))
{
[Link]((char*)&t,sizeof(t));
}
cout<<"contents copied:"<<endl;
[Link]( );
[Link]( );
}
void display_contents( )
{
fstream fin;
Text t;
[Link]("[Link]",ios::in|ios::binary);
while([Link]((char*)&t,sizeof(t)))
{
[Link]( );
}
[Link]( );
}
int main( )
{
int choice;
while(1)
{
cout<<"[Link] Details:"<<endl;
cout<<"[Link] contents"<<endl;
cout<<"[Link] copied contents:"<<endl;
cout<<"[Link]:"<<endl;
cout<<"Enter the choice:"<<endl;
cin>>choice;
switch(choice)
{
case 1:
add_details( );
break;
case 2:
copy_contents( );
break;
case 3:
display_contents( );
break;
case 4:
exit(0);
default:
cout<<"The choice you entered is wrong:"<<endl;
}
}
return 0;
}
Q)WAP to write records of students in a file and display
the records of the students according to the descending
order of marks obtained by them.
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
class student
{
char name[30];
int roll;
float marks;
public:
void input( )
{
cout<<“Enter the name of an student:”<<endl;
cin>>name;
cout<<“Enter the roll of the student:”<<endl;
cin>>roll;
cout<<“Enter the marks obtained:”<<endl;
cin>>marks;
}
void display( )
{
cout<<“Name of the student=“<<name<<endl;
cout<<“Roll of the student=“<<roll<<endl;
cout<<“Marks obtained=“<<marks<<endl;
}
float ret_marks( )
{
return marks;
}
};
void add_records( )
{
student s[10];
fstream fout;
[Link](“[Link]”,ios::out|ios::app|ios::binary);
for(int i=0;i<10;i++)
{
s[i].input( );
[Link]((char*)&s[i],sizeof(s[i]));
}
[Link]( );
}
void display_records( )
{
student s[10];
fstream fin;
[Link](“[Link]”,ios::in|ios::binary);
for(int i=0;i<10;i++)
{
[Link]((char*)&s[i],sizeof(s[i]));
}
for(int i=0;i<9;i++)
for(int j=i+1;j<10;j++)
{
if(s[j].ret_marks( )>s[i].ret_marks( ))
{
student temp=s[j];
s[j]=s[i];
s[i]=temp;
}
}
for(int i=0;i<10;i++)
{
s[i].display();
}
[Link]( );
}
int main()
{
int choice;
while(1)
{
cout<<“[Link] records to the file:”<<endl;
cout<<“[Link] records from the file:”<<endl;
cout<<“[Link]”<<endl;
cout<<“Enter the choice:”<<endl;
cin>>choice;
switch(choice)
{
case 1:
add_records( );
break;
case 2:
display_records();
break;
case 3:
exit(0);
default:
cout<<“The choice you entered is wrong:”<<endl;
}
}
return 0;
}
File access pointer and their manipulators:(Imp)
-Each file has two associated pointers known as file pointers.
One of them is called the input pointer(or get pointer) and the
other is called the output pointer(or put pointer).
-We can use these pointers to move through the file while
reading or writing(these pointers help to implement random
access i.e. we can access any point in the file).
-The input pointer(get pointer) is used for reading the contents
of a given file location.
-The output pointer(put pointer) is used for writing the given
file location.
-Each time an input or output operation takes place the
appropriate pointer is automatically advanced.
Default Action:
H E L L O W O R L D
Input Pointer
Open for read only
H E L L O W O R L D
Output Pointer
Open in append mode
(for writing more data)
Output pointer
(Open for writing only)
There are four function related to manipulation of file access pointers
and they are as follows
1)seekg( ):Moves get pointer(input pointer) to a specified location.
2)seekp( ):Moves put pointer(output pointer) to a specified location.
3)tellg( ):Gives the current position of the get pointer.
4)tellp( ):Gives the current position of the put pointer.
Example:
ifstream fin;
[Link](10);
-Moves the get(input) pointer to the byte number
10([Link] pointer will be pointing to the 11th byte in the
file)
ofstream fout;
[Link](“Hello”,ios::app);
int p=[Link]( );
The output pointer is moved to the end of the file “Hello”
and the value of p will represent the number of bytes in
the file.
-seek functions seekg( ) and seekp( ) can also be used with two
arguments as:
seekg(of/set,refposition);
seekp(of/set,refposition);
of/set-is the number of bytes the file pointer to be moved from the
location specified by the parameter refposition which takes one of the
following.
ios::beg-start from the file
ios::cur-current position of the pointer.
ios::end-end of file
Examples:
- [Link](20,ios::beg)-Will move get pointer of ifstream to 20 byte
forward from the beginning of the file
- [Link](-40,ios::end)-Will move put pointer to 40 bytes back from
the end of the file
[Link](-10,ios::cur)-Will move get pointer 10 byte back
from the current location in the file.
Example:
char ch;
ifstream fin(“[Link]”,ios::binary);
[Link](5);
[Link]((char*)&ch,sizeof(ch));
[Link](-3,ios::cur);
[Link]((char*)&ch,sizeof(ch));
Here, first the character will be read from 5th position of the
file “[Link]” and another character from 3rd position of the
file(because first read moves the file access pointer to the 6th
position).
First: Seekg(5)
0 1 2 3 4 5
1st 2nd 3rd 4th 5th 6th
Second: seekg(-3,ios::cur)
0 1 2 3 4 5
1st 2nd 3rd 4th 5th 6th
Example:
ofstream fout(“[Link]”);
[Link](5);
fout<<“**”;
[Link](-2,ios::cur);
fout<<“#”;
-Here, first will be written ‘**’ to the 6th and 7th
position and points to 8th position. Again returns back
to the 6th position and writes ‘#’ to it.
0 1 2 3 4 5 6 7 8 9
H E L L O W O R L D
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
H E L L O W O R L D
Seekp(5)
H E L L O * * R L D
fout<<“**”;
H E L L O * * R L D
Seekp(-2,ios::cur);
H E L L O # * R L D
fout<<“#”;
Example program of tellg( ) and tellp( ):
#include<iostream>
#include<fstream>
using namespace std;
int main( )
{
ifstream fin;
ofstream fout; 0 1 2 3 4 5
[Link](“[Link]”); a n g r y
fout<<“angry”;
Put po-
int n=[Link]( );
inter
[Link]( ); 0 1 2 3 4 5
cout<<“Position of put pointer=“<<n<<endl;
a n g r y
[Link](“[Link]”);
int m=[Link]( );
[Link]( ); Get pointer
cout<<“Position of get pointer=“<<m<<endl;
return 0;
}
Example Program of Random Access:
Q)WAP to store and retrieve all the information of the students in a
file. Also make sure to read the nth information(record) of a student
from the file and display it.
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
class student
{
char name[30];
int roll;
float marks;
public:
void input( )
{
cout<<“Enter the name of the student:”<<endl;
cin>>name;
cout<<“Enter the roll number of the student:”<<endl;
cin>>roll;
cout<<“Enter the marks obtained by the student:”<<endl;
cin>>marks;
}
void display( )
{
cout<<“Name of the student=“<<name<<endl;
cout<<“Roll of the student=“<<roll<<endl;
cout<<“Marks obtained by the student=“<<marks<<endl;
}
};
void adddetails( )
{
student s;
fstream fout;
[Link](“[Link]”,ios::out|ios::app|ios::binary);
[Link]( );
[Link]((char*)&s,sizeof(s));
[Link]( );
}
void displayrecords( )
{
student s;
fstream fin;
[Link](“[Link]”,ios::in|ios::binary);
while([Link]((char*)&s,sizeof(s)))
{
[Link]( );
}
[Link]( );
}
void display_nth_record( )
{
student s;
fstream fin;
int count=0;
int n;
[Link](“[Link]”,ios::in|ios::binary);
while([Link]((char*)&s,sizeof(s)))
{
count ++;
}
[Link]( );
if(count==0)
{
cout<<“Record doesnot exist:”<<endl;
}
else
{
cout<<“The total number of records=”<<count<<endl;
[Link](“[Link]”,ios::in|ios::binary);
cout<<“Enter the number of record to read:”<<endl;
cin>>n;
if(n>0 && n<=count)
{
[Link]((n-1)*sizeof(s));
[Link]((char*)&s,sizeof(s));
[Link]( );
[Link]( );
}
}
}
int main( )
{
int choice;
while(1)
{
cout<<“[Link] Details:”<<endl;
cout<<“[Link] All Records:”<<endl;
cout<<“[Link] nth Record:”<<endl;
cout<<“[Link]:”<<endl;
cout<<“Enter the choice:”<<endl;
cin>>choice;
switch(choice)
{
case 1:
adddetails( );
break;
case 2:
displayrecords();
case 3:
display_nth_record( );
break;
case 4:
exit(0);
default:
cout<<“The choice you entered is wrong:”<<endl;
}
}
return 0;
}
Note: To modify or update the record:
void modify( )
{
fstream fout;
student s;
int roll,flag=0;
int size=sizeof(s);
int count=0;
int location;
cout<<“Enter the roll number to be modified:”<<endl;
cin>>roll;
[Link](“[Link]”,ios::ate|ios::out|ios::in|ios::binary);
[Link](0);
while([Link]((char*)&s,sizeof(s)))
{
count ++;
if([Link](roll))
{
[Link]( );
location=size*(count-1);
[Link](location,ios::beg);
[Link]((char*)&s,sizeof(s));
cout<<“Modified”<<endl;
flag=1;
break;
}
}
if(flag==0)
cout<<“Not found”<<endl;
[Link]( );
}