Oop Chapter 05
Oop Chapter 05
What is stream?
• C++ IO are based on streams, which are sequence of bytes flowing in and out of
the programs. A C++ stream is a flow of data into or out of a program, such as the
data written to cout or read from cin.
• C++ provides standard iostream library to operate with streams.
• The iostream is an object-oriented library which provides Input/Output
functionality using streams.
In the above figure, ios is the base class. The iostream class is derived
from istream and ostream classes. The ifstream and ofstream are derived
from istream and ostream, respectively. These classes handle input and output with the
disk files.
The filebuf class contains input and output operations with files. The streambuf class
does not organize streams for input and output operations, only derived classes
of streambuf performs I/O operations. These derived classes arrange a space for
keeping input data and for sending output data.
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.
The istream and ostream invokes the filebuf functions to perform the insertion or
extraction on the streams.
In Files we store data i.e. text or binary data permanently and use these data to read or
write in the form of input output operations by transferring bytes of data. So we use the
term File Streams/File handling. We use the header file <fstream.h>
• ofstream: It represents output Stream and this is used for writing in files.
• ifstream: It represents input Stream and this is used for reading from files.
• fstream: It represents both output Stream and input Stream. So it can read from
files and write to files.
Input/Output Streams
Creating/Opening a File
We create/open a file by specifying new path of the file and mode of operation.
Operations can be reading, writing, appending and truncating. Syntax for file
creation: FilePointer.open("Path",ios::mode);
#include<iostream.h>
#include<conio.h>
#include <fstream.h>
Writing to a File
#include <iostream.h>
#include<conio.h>
#include <fstream.h>
int main()
{
fstream st; // Step 1: Creating object of fstream class
st.open("E:\study.txt",ios::out); // Step 2: Creating new file
if(!st) // Step 3: Checking whether file exist
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
st<<"Hello"; // Step 4: Writing to file
st.close(); // Step 5: Closing file
}
getch();
return 0;
}
Here we are sending output to a file. So, we use ios::out. As given in the program,
information typed inside the quotes after "FilePointer <<" will be passed to output file.
int main()
{
fstream st; // step 1: Creating object of fstream class
st.open("E:\study.txt",ios::in); // Step 2: Creating new file
if(!st) // Step 3: Checking whether file exist
{
cout<<"No such file";
}
else
{
char ch;
while (!st.eof())
{
st >>ch; // Step 4: Reading from file
cout << ch; // Message Read from file
}
st.close(); // Step 5: Closing file
}
getch();
return 0;
}
Here we are reading input from a file. So, we use ios::in. As given in the program,
information from the output file is obtained with the help of following
syntax "FilePointer >>variable".
Close a File
It is done by FilePointer.close().
#include <iostream.h>
#include<conio.h>
#include <fstream.h>
int main()
{
fstream st; // Step 1: Creating object of fstream class
st.open("E:\study.txt",ios::out); // Step 2: Creating new file
st.close(); // Step 4: Closing file
getch();
return 0;
}
In order to open a file with a stream object open() member function is used.
open (filename, mode);
Where filename is a null-terminated character sequence of type const char * (the same
type that string literals have) representing the name of the file to be opened, and mode
is an optional parameter with a combination of the following flags:
Mode Description
ios::ate Write all output to the end of file (even if file position
pointer is moved with seekp)
ios::app Open a file for output and move to the end of the
existing data (normally used to append data to a file, but
data can be written anywhere in the file
ios::in The original file (if it exists) will not be truncated
ios::out Open a file for output (default for ofstream objects)
ios::trunc Discard the file's contents if it exists (this is also the
default action for ios::out, if ios::ate, ios::app,
or ios::in are not specified)
ios::binary Opens the file in binary mode (the default is text mode)
ios::nocreate Open fails if the file does not exist
ios::noreplace Open files if the file already exists.
C++ provides a special function, eof( ), that returns nonzero (meaning TRUE) when
there are no more data to be read from an input file stream, and zero (meaning FALSE)
otherwise.
Syntax: filepointer.tellp()
Note: For seekp and seekg three reference points are passed:
ios::beg - beginning of the file
ios::cur - current position in the file
ios::end - end of the file
Below is a program to show importance of tellp, tellg, seekp and seekg:
#include <iostream.h>
#include<conio.h>
#include <fstream.h>
int main()
{
fstream st; // Creating object of fstream class
st.open("E:\study.txt",ios::out); // Creating new file
if(!st) // Checking whether file exist
{
cout<<"File creation failed";
}
else
{
cout<<"New file created"<<endl;
st<<"Hello Friends"; //Writing to file
// Checking the file pointer position
cout<<"File Pointer Position is "<<st.tellp()<<endl;
fstream fout;
fout.write( (char *) &obj, sizeof(obj) );
#include<fstream.h>
#include<conio.h>
class Student
{
int roll;
char name[25];
float marks;
void getdata()
{
cout<<"\n\nEnter Roll : ";
cin>>roll;
void main()
{
Student S;
char ch='n';
do
{
S.AddRecord();
cout<<"\n\nDo you want to add another data (y/n) : ";
ch = getche();
} while(ch=='y' || ch=='Y');
cout<<"\nData written successfully...";
}
Output :
Enter Roll : 1
Enter Roll : 2
Enter Name : Kaushal
Enter Marks : 72.65
Enter Roll : 3
Enter Name : Vishwas
Enter Marks : 82.65
fstream fin;
fin.read( (char *) &obj, sizeof(obj) );
#include<fstream.h>
#include<conio.h>
class Student
{
int roll;
char name[25];
float marks;
void putdata()
{
cout<<"\n\t"<<roll<<"\t"<<name<<"\t"<<marks;
}
public:
void Display()
{
fstream f;
Student Stu;
f.open("Student.dat",ios::in|ios::binary);
cout<<"\n\tRoll\tName\tMarks\n";
while( (f.read((char*)&Stu,sizeof(Stu))) != NULL )
Stu.putdata();
f.close();
}
};
void main()
{
Student S;
S.Display();
}
Output :
Roll Name Marks
1 Ashish 78.53
2 Kaushal 72.65
3 Vishwas 82.65