Sinhgad College of Engineering
Vadgaon Bk. Pune
Approved by AICTE New Delhi Recognized by Govt. of Maharashtra
Affiliated to Savitribai Phule Pune University
Accredited by NAAC with A+ Grade
Subject:- 210243: Object Oriented Programming.
Unit-IV File & Streams
Mr. AJIT M. KARANJKAR
Assistant. Professor.
Department of Computer Engineering,
Sinhgad College Of Engineering Vadgaon Bk, Pune-041
Email:- amkaranjkar.scoe@sinhgad.edu
30-09-2024 1
Contents:
❑ Files & Streams.
Data Hierarchy , Stream and Files, stream classes ,stream errors, Disk File,
I/O with stream, File pointer, and Error handling in file I/O, File I/O With
member Functions, Overloading the extraction and Insertion Operators,
Memory as a stream Object, Command Line Argument, Printer Output.
UNIT-III Polymorphism
06-10-2021 2
Department Of Computer Engineering
4. FILES & STREAMS
UNIT-III Polymorphism
06-10-2021 3
Department Of Computer Engineering
5.1 Data Hierarchy
5.1Data Hierarchy:
•Ultimately all data items that computers process are reduced to combinations
of 0s and 1s.
•The smallest data items computers support is called bit. Each data item or bit
can assume either the value 0 or the value1.
UNIT-IV Files & Streams
06-10-2021 4
Department Of Computer Engineering
5.2 Streams & Files
•Stream work with all built in data types
•We can overload stream by overloading <<insertion operator.
•Stream is abstraction which represents device which input and output
operation are performed.
•It is mainly declare in header file <iostream>
UNIT-IV Files & Streams
06-10-2021 5
Department Of Computer Engineering
5.3 Stream And Files
Input Device Input stream
Program
Output Device Output Stream
Fig: C++ Streams
UNIT-IV Files & Streams
06-10-2021 6
Department Of Computer Engineering
5.3 Stream Class
• In C++ there are number of stream classes for defining various streams related with files
and for doing input-output operations.
• All these classes are defined in the file iostream.h
• All these classes are declared in header files.
• These input output classes is called as stream classes.
UNIT-IV Files & Streams
06-10-2021 7
Department Of Computer Engineering
5.3 Stream Class
ios
Istream Ostream
IOstream
Ofstream
Ifstream
fstream
Fig: Streams classes in C++
UNIT-IV Files & Streams
06-10-2021 8
Department Of Computer Engineering
5.3 Stream Class
• The ios class: The ios class is responsible for providing all input and output facilities to
all other stream classes.
• The istream class: This class is responsible for handling input stream. It provides
number of function for handling chars, strings and objects such as get, getline, read,
ignore, putback etc..
• The ostream class: This class is responsible for handling output stream. It provides
number of function for handling chars, strings and objects such as write, put etc..
UNIT-IV Files & Streams
06-10-2021 9
Department Of Computer Engineering
5.3 Stream Class
• The iostream: This class is responsible for handling both input and output stream as both
istream class and ostream class is inherited into it.
⮚ It provides function of both istream class and ostream class for handling chars,
strings and objects such as get, getline, read, ignore, putback, put, write etc..
• ostream_withassign class: This class is variant of ostream that allows object
assignment.
⮚ The predefined objects cout, cerr, clog are objects of this class and thus may be
reassigned at run time to a different ostream object.
UNIT-IV Files & Streams
06-10-2021 10
Department Of Computer Engineering
5.3 Stream Class
• The iostream: This class is responsible for handling both input and output stream as both
istream class and ostream class is inherited into it.
⮚ It provides function of both istream class and ostream class for handling chars,
strings and objects such as get, getline, read, ignore, putback, put, write etc..
• ostream_withassign class: This class is variant of ostream that allows object
assignment.
⮚ The predefined objects cout, cerr, clog are objects of this class and thus may be
reassigned at run time to a different ostream object.
UNIT-IV Files & Streams
06-10-2021 11
Department Of Computer Engineering
5.3 Stream Class
• Standard Output Stream (Cout):
• cout is object of Ostream class.
• cout object is connected to standard output device. cout, << is used to write to standard
output.
• It is used with insertion operator (<<). We can overload << to display object.
UNIT-IV Files & Streams
06-10-2021 12
Department Of Computer Engineering
5.3 Stream Class
• Example:
#include<iostream>
using namespace std;
int main()
{
char str[ ]=“Hello word in c++”;
cout<<str;
• Output
Hello Word in C++
UNIT-IV Files & Streams
06-10-2021 13
Department Of Computer Engineering
5.3 Stream Class
• Example: 2
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
class str_op
{
private:
char str[40];
public:
void get_string()
{
cout<<“\n Enter String”;
cin>>str;
}
friend void operator<<(ostream &a,str_op&b)
{
a<<b.str;
}
};
UNIT-IV Files & Streams
06-10-2021 14
Department Of Computer Engineering
5.3 Stream Class
int main( )
{
str_op s1;
s1.get_string();
cout<<s1;
return 0;
Output:
Enter String: Amit
Amit
UNIT-IV Files & Streams
06-10-2021 15
Department Of Computer Engineering
5.3 Stream Class
• Standard Input Stream (Cin):
• It is object of istream class .cin object is attached to standard input stream.
• The cin object in C++ is an object of class iostream. It is used to accept the input from the
standard input device i.e. keyboard.
• It is associated with the standard C input stream stdin. The extraction operator(>>) is used
along with the object cin for reading inputs.
UNIT-IV Files & Streams
06-10-2021 16
Department Of Computer Engineering
5.3 Stream Class
• Example:
#include<iostream>
using namespace std;
int main()
{
char name[50];
cout<<”Please Enter your name:”;
cin>>name;
cout<<“Your name is :”<<name<<endl;
}
Output
Please Enter your name: Amit
Your name is: Amit
UNIT-IV Files & Streams
06-10-2021 17
Department Of Computer Engineering
5.3 Stream Class
• Standard Error Stream (Cerr):
• Standard error stream (cerr): cerr is the standard error stream which is used to output
the errors. It is an instance of the ostream class.
• As cerr stream is un-buffered so it is used when we need to display the error message
immediately and does not store the error message to display later.
• The object of class ostream that represents the standard error stream oriented to narrow
characters(of type char). It corresponds to the C stream stderr.
• The “c” in cerr refers to “character” and ‘err’ means “error”, Hence cerr means
“character error”. It is always a good practice to use cerr to display errors.
UNIT-IV Files & Streams
06-10-2021 18
Department Of Computer Engineering
5.3 Stream Class
• Example:
#include<iostream>
using namespace std;
int main()
{
char str[]=“Unable to read.....”;
cerr<<“Error Message:”<<str<<endl;
Output
Error Message: Unable to read
UNIT-IV Files & Streams
06-10-2021 19
Department Of Computer Engineering
5.4 Stream Errors
• Input Output systems in c++ is based on stream.
• Stream is nothing but sequence of characters .stream works well with cin and cout for
input and output purpose.
• It corresponds to the C stream stderr. The standard error stream is a destination of
characters determined by the environment.
• As an object of class ostream, characters can be written to it either as formatted data
using the insertion operator (operator<<) or as unformatted data, using member functions
such as write.
UNIT-IV Files & Streams
06-10-2021 20
Department Of Computer Engineering
5.5 Files
• Files are used to store data in a storage device permanently. File handling provides a
mechanism to store the output of a program in a file and to perform various operations on
it.
• In C++ we have a set of file handling methods. These include ifstream, ofstream, and
fstream.
• It means we read and write the data from variables.
UNIT-IV Files & Streams
06-10-2021 21
Department Of Computer Engineering
5.5 Files
• In C++, files are mainly deal by using three classes fstream, ifstream, ofstream.
• ofstream: This Stream class signifies the output file stream and is applied to create files
for writing information to files
• ifstream: This Stream class signifies the input file stream and is applied for reading
information from files
• fstream: This Stream class can be used for both read and write from/to files.
UNIT-IV Files & Streams
06-10-2021 22
Department Of Computer Engineering
5.5 Files
• C++ provides us with the following operations in File Handling:
Create file. Open File.
Read from file. Write to file.
Close file Append contents in file
Modify File Truncate file.
• There are many more function available to manipulate the information in the file .
• Program can store the information in the file or read the data from file. Files can be
character or binary files.
UNIT-IV Files & Streams
06-10-2021 23
Department Of Computer Engineering
5.5 Files
5.5.1 File Handling in C++
• As we already know input output is handled in c++ with the help of stream classes
• I/O systems handles file more like input output with console.
• Stream which feeds data to program is known as input stream and stream which receives
the data is known as Output stream.
• Stream which feeds data to program through file is known as file input stream and
stream which store program data to file is known as file Output stream.
UNIT-IV Files & Streams
06-10-2021 24
Department Of Computer Engineering
5.5 Files
5.5.1 File Handling in C++
• The working of input output file streams are shown in fig.
UNIT-IV Files & Streams
06-10-2021 25
Department Of Computer Engineering
5.5 Files
5.5.2 C++ Classes for File Handling.
• In the fig. ifstream , ofstream, and fstream Classes are file classes
ios
Istream Ostream
IOstream
Ofstream
Ifstream
fstream
Fig: Streams classes in C++
UNIT-IV Files & Streams
06-10-2021 26
Department Of Computer Engineering
5.6 Disk File I/O with Streams
• Disk File I/O with Streams
• Most programs need to save data to disk files and read it back in.
• Working with disk files requires another set of classes: ifstream for input, fstream for
both input and output, and ofstream for output.
• Objects of these classes can be associated with disk files, and we can use their member
functions to read and write to the files.
✔1. Opening File
✔2.Closing File
✔3. Writing data to File.
✔4.Reading data to File.
✔5.Detecting end of file.
UNIT-IV Files & Streams
06-10-2021 27
Department Of Computer Engineering
5.6 Disk File I/O with Streams
• 5.6.1 Opening file:
• The first operation generally performed on an object of one of these classes to use a file
is the procedure known as to opening a file.
• An open file is represented within a program by a stream and any input or output task
performed on this stream will be applied to the physical file associated with it.
The syntax of opening a file in C++ is:
open (filename, mode);
UNIT-IV Files & Streams
06-10-2021 28
Department Of Computer Engineering
5.6 Disk File I/O with Streams
• Example
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
cout<<“\n File Opening Operation ”;
ofstream fout(“c:\\example.txt”);
return 0;
}
Output:
File Opening Operation
UNIT-IV Files & Streams
06-10-2021 29
Department Of Computer Engineering
5.6 Disk File I/O with Streams
• 5.6.2 Closing file:
• Whenever we open file we need to close it .
• Generally C++ automatically closes the file. No need to close it explicitly.
• But it is better to close file explicitly. It is possible by close() function.
The syntax of opening a file in C++ is:
fout.close ( );
UNIT-IV Files & Streams
06-10-2021 30
Department Of Computer Engineering
5.6 Disk File I/O with Streams
• Example
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
cout<<“\n File Opening Operation ”;
ofstream fout(“c:\\example.txt”);
fout.close();
return 0;
}
Output:
File closing Operation
UNIT-IV Files & Streams
06-10-2021 31
Department Of Computer Engineering
5.6 Disk File I/O with Streams
5.6.3 . Write data to file.
• For writing data to file we need to create or open file first.
• If file is existing then file will be truncated.
• We can write data to file using << put operator more like operator with cout statement.
• You can write to file right from your C++ program. You use stream insertion operator
(<<) for this.
UNIT-IV Files & Streams
06-10-2021 32
Department Of Computer Engineering
5.6 Disk File I/O with Streams
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream my_file; my_file.open("my_file.txt", ios::out);
if (!my_file)
{
cout << "File not created!";
}
else
{
cout << "File created successfully!"; my_file << "Guru99";
my_file.close();
}
return 0;
}
UNIT-IV Files & Streams
06-10-2021 33
Department Of Computer Engineering
5.6 Disk File I/O with Streams
5.6.4. Reading data to file.
• To read from a file, use either the ifstream or fstream class, and the name of the file.
• You can read information from files into your C++ program. This is possible using
stream extraction operator (>>). You use the operator in the same way you use it to read
user input from the keyboard.
• Now we will see how to read data from file.
• It is possible to read data form file.
• It is more like cin and>> UNIT-IV Files & Streams
06-10-2021 34
Department Of Computer Engineering
5.6 Disk File I/O with Streams
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ofstream fout;
fout.open("sample.txt");//create file
fout<<"Hello Student";//write in file.
fout.close();
string mytext;
ifstream fin("sample.txt",ios::in);
if(!fin)
{
cout<<"No such file";
}
else
{
UNIT-IV Files & Streams
06-10-2021 35
Department Of Computer Engineering
5.6 Disk File I/O with Streams
while(getline(fin,mytext))
{
cout<<mytext;
}
fin.close();
//fout.close();
}
return 0;
}
Output:
Hello Student
UNIT-IV Files & Streams
06-10-2021 36
Department Of Computer Engineering
5.6 Disk File I/O with Streams
5.6.5 . Detecting end of File.
• It is necessary to detect the end of file at the time reading data from file.
• It is possible using different options.
• ifstreams object returns 0 after reaching the end of file during the reading .
• We can detect end of file using eof() function which is part of ifstream class.
UNIT-IV Files & Streams
06-10-2021 37
Department Of Computer Engineering
5.6 Disk File I/O with Streams
Example:
#include <iostream>
#include <fstream>
int main ()
{
std::ifstream is("example.txt");
char c; while (is.get(c))
std::cout << c; if (is.eof())
std::cout << "[EoF reached]\n";
else
std::cout << "[error reading]\n"; is.close();
return 0;
}
UNIT-IV Files & Streams
06-10-2021 38
Department Of Computer Engineering
5.6 Disk File I/O with Streams
5.6.6 . File Opening Mode
• We have used ifstream and ofstream constructors and the function open() to create new
files as well as to open the existing files.
• We can open file in different modes also.
• Syntax for opening file in different mode is as follows :
Object_name.open(“file_name”,mode);
UNIT-IV Files & Streams
06-10-2021 39
Department Of Computer Engineering
5.6 Disk File I/O with Streams
UNIT-IV Files & Streams
06-10-2021 40
Department Of Computer Engineering
5.6 Disk File I/O with Streams
5.6.6 . Reading and Writing class Object from file.
• Unlike built in data types we can write object in file also.
• Generally object are written in binary mode.
• Object is important part in Object oriented programming . So we focus or writing or
reading object in file.
• Read and write function syntax is given below:
File_object.read(address_of _object, size_of _object);
File_object.write(address_of _object, size_of _object);
UNIT-IV Files & Streams
06-10-2021 41
Department Of Computer Engineering
5.6 Disk File I/O with Streams
Example:
#include <iostream>
#include <fstream>
using namespace std; // Class to define the properties
class Employee
{
public:
string Name;
int Employee_ID;
int Salary;
};
int main( )
{
Employee Emp_1;
Emp_1.Name="John";
Emp_1.Employee_ID=2121;
Emp_1.Salary=11000; //Wriring this data to Employee.txt ofstream file1;
UNIT-IV Files & Streams
06-10-2021 42
Department Of Computer Engineering
5.6 Disk File I/O with Streams
Example:
Emp_1.Salary=11000; //Wriring this data to Employee.txt
ofstream file1;
file1.open("Employee.txt", ios::app);
file1.write((char*)&Emp_1,sizeof(Emp_1));
file1.close(); //Reading data from EMployee.txt
ifstream file2;
file2.open("Employee.txt",ios::in);
file2.seekg(0);
file2.read((char*)&Emp_1,sizeof(Emp_1));
cout<<"\nName :“,Emp_1.Name;
cout<<"\nEmployee ID :”,Emp_1.Employee_ID;
cout<<"\nSalary “<<,MM,Emp_1.Salary;
file2.close();
return 0;
}
UNIT-IV Files & Streams
06-10-2021 43
Department Of Computer Engineering
5.6 Disk File I/O with Streams
Output:
Name: John
Employee ID: 2121
Salary: 11000
UNIT-IV Files & Streams
06-10-2021 44
Department Of Computer Engineering
5.7 File Pointers
• Each File has two file pointers associated with it.
• One is input pointer and another is output pointer which are useful for reading and
writing purpose.
• We can move this pointer to and from reading and writing file.
• We can read or write data on specified location with file pointers.
• Whenever we read or write data pointer is automatically advances to next location.
UNIT-IV Files & Streams
06-10-2021 45
Department Of Computer Engineering
5.7 File Pointers
“hello” file
• Open for reading only
H E L L O W O R L D
input pointer.
• Open in append Mode
(for writing more data)
H E L L O W O R L D
output pointer
Output pointer for writing
Output Pointer
Fig: File pointer position
UNIT-IV Files & Streams
06-10-2021 46
Department Of Computer Engineering
5.7 File Pointers
UNIT-IV Files & Streams
06-10-2021 47
Department Of Computer Engineering
5.8 Error Handling In File I/O
• Error handling is very important in file handling.
• So far we have been opening and using the files for reading and writing on the
assumption that everything is fine with the files.
• There may be error present during file handling.
• Some of the errors are file not found , could not open file , could not read file, could not
write in the file etc,
• But efficient programming we need to check their condtions to get the desired outcomes
from the program.
UNIT-IV Files & Streams
06-10-2021 48
Department Of Computer Engineering
5.8 Error Handling In File I/O
Example:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int roll;
char name[10];
float marks;
ifstream file;
file.open("C:\\TURBOC3\\BIN\\student7.txt");
if(file.is_open())
{
cout<<"File Successfully Open";
file.close();
} UNIT-IV Files & Streams
06-10-2021 49
else Department Of Computer Engineering
5.8 Error Handling In File I/O
else
{
cout<<"Error Opening File";
}
return 0;
}
Output:
Error Opening File
UNIT-IV Files & Streams
06-10-2021 50
Department Of Computer Engineering
5.9 File I/O With Member Function
• The object cin is a global object in the class istream (input stream) and the global object
cout is a member of the class ostream (output stream).
• File stream come in two flavours :
• The class ifstream (input file stream ) inherits from istream and
• The class ofstream (output file stream)inherits from ostream.
• Thus all of the member functions and operators that you can apply to an istream and
ofstream object that can also be applied to ifstream and ofstream objects.
UNIT-IV Files & Streams
06-10-2021 51
Department Of Computer Engineering
5.9 File I/O With Member Function
Example:
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
int main()
{
char text[200];
fstream file;
file.open("C:\\TURBOC3\\BIN\\student7.txt",ios::out|ios::in);
cout<<"Write text to be written on file"<<endl;
cin.getline(text,sizeof(text));
file<<text<<endl;
file>>text;
cout<<text<<endl;
file.close();
getch();
return 0;
} 06-10-2021
UNIT-IV Files & Streams
52
Department Of Computer Engineering
5.9 File I/O With Member Function
Output:
Hello
Student
UNIT-IV Files & Streams
06-10-2021 53
Department Of Computer Engineering
5.10 Overloading the Extraction and Insertion Operators
• With cin and cout we can handle all built in data types for input and output;
• >>and<< is used within cin and cout to perform the input output operation.
• It is not possible to deal with user defined data types using cin and cout.
• The operator Overloading function friend functions so that we can call it without creating
the object of the class.
• Without operator overloading we need to deal with all member of class individually.
UNIT-IV Files & Streams
06-10-2021 54
Department Of Computer Engineering
5.10 Overloading the Extraction and Insertion Operators
Example:
#include<iostream.h>
#include<conio.h>
class dist
{
private:
int f;
int i;
public:
dist ()
{ f=0;
i=0;
}
dist(int feet ,int in)
{ f=feet;
i=in;
}
UNIT-IV Files & Streams
06-10-2021 55
Department Of Computer Engineering
5.10 Overloading the Extraction and Insertion Operators
Example:
friend ostream &operator<<(ostream & out,const dist &A)
{
out<<"Feet:"<<A.f<<"Inches:"<<A.i;
return out;
}
friend istream &operator>>(istream &in,const dist &A)
{
in>>A.f>>A.i;
return in;
}
};
int main()
{ dist A(15,20),B(25,30),C;
cout<<"Enter Value";
cin>>C;
cout<<"This is 1st Distance: "<<A<<"\n";
UNIT-IV Files & Streams
06-10-2021 56
Department Of Computer Engineering
5.10 Overloading the Extraction and Insertion Operators
cout<<"This is 2nd Distance: "<<B<<"\n";
cout<<"This is 3rd Distance: "<<C<<"\n";
getch();
return 0;
}
Output:
Enter the value of object:
40 45
This is 1st distance : Feet :15 inches :20
This is 2nd distance : Feet :25 inches :30
This is 3rd distance : Feet :40 inches :45
UNIT-IV Files & Streams
06-10-2021 57
Department Of Computer Engineering
5.11 Memory as a stream Object:
• We can use section of memory to store stream object.
• After creating object we can read or write data in stream object more like file.
• It is useful when we need to format the output.
• It is common in calling functions in GUI environment.
• For writing to memory we use ostrstream class.It is subclass of ostream class only.
• For Reading to memory we use istrstream class. It is subclass of istream class only.
• For reading and writing purpose we can use strstream class.
UNIT-IV Files & Streams
06-10-2021 58
Department Of Computer Engineering
5.11 Memory as a stream Object:
Example:
#include<strstream>
#include<iostream>
#include<iomanip>
using namespace std;
const int MAX=80;
int main()
{ char ch='a';
int i=100;
double num=1234.567;
char str1[]="abcd";
char str2[]="efgh";
char buff[MAX];
ostrstream my_object(buff,MAX);
my_object<<"\n ch ="<<ch;
my_object<<"\n i="<<i;
my_object<<setiosflags(ios::fixed)<<setprecision(2)<<"\n double"<<num;
UNIT-IV Files & Streams
06-10-2021 59
Department Of Computer Engineering
5.11 Memory as a stream Object:
my_object<<"\n First String="<<str1;
my_object<<"\n Second String="<<str1;
cout<<buff;
return 0;
}
Output:
ch=a
i=100
double=1234.567
first string=abcd
second string efgh
UNIT-IV Files & Streams
06-10-2021 60
Department Of Computer Engineering
5.12 Command Line Arguments:
• C,C++ too supports a feature that facilitates the supply of arguments to the main()
function.
• The command-line arguments are typed by the user and are delimited by a space. The
first argument is always the filename (command name) and contains the program is
executed.
• The main () function which we have been using up to now without any arguments can
take two arguments as shown below:
• main(int args, char * argv[])
UNIT-IV Files & Streams
06-10-2021 61
Department Of Computer Engineering
5.12 Command Line Arguments:
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char *argv[])
{
cout<<"Hi student How are you...";
cout<<"\n Welcome to C++ Programming";
cout<<"\n Number of arguments are:";
for(int i=0;i<argc;i++)
{
cout<<argv[i];
}
return 0;
}
Output:
Hi student How are you...
Welcome to C++ Programming.
Number of arguments are: C:\Cpp Program\sample.exe
UNIT-IV Files & Streams
06-10-2021 62
Department Of Computer Engineering
5.13 Printer Output:
• It is easy to used console based program to send data to printer.
• Many special filenames for hardware devices are defined by OS.
• Generally printer Is connected to first parallel port of the system.
• So it is recommended to use lpt1 as filename to print through the printer.
UNIT-IV Files & Streams
06-10-2021 63
Department Of Computer Engineering
5.13 Printer Output:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{ cout<<"\n Printing output using printer";
ofstream print("File");
if(!print)
{
cout<<"\n No printer connected";
return 1;
}
print<<"\n This is first line printed ";
print<<"\n Number :"<<12345;
print<<"\n Float: "<<345.567;
print<<"\n char"<<'c';
print.close();
return 0; UNIT-IV Files & Streams
06-10-2021 64
} Department Of Computer Engineering
5.13 Printer Output:
Output:
This is first line printed
Number :12345
Float: 345.567
char c
UNIT-IV Files & Streams
06-10-2021 65
Department Of Computer Engineering