1
File Handling in C++
File :- File is a collection of similar type of information, which stored permanently in secondary
memory (HDD, FDD) and File Handling is a mechanism which provide different kind of
operation on File.
Operation on file :-
1. Open a file
2. Close file
3. Read from file
4. Write into file
5. Insert into file
6. Append file
7. Search file
8. Update file
9. Delete from file
10. Remove file
11. Rename file
12. Sorting of file
Block Diagram of File Handling in C++
Primary Memory(RAM)
BUFFER
DATA(Info)
HDD
ifstream ofstream
PROGRAM
VAR
Monitor KB
Reading Operation:- HDD Buffer ifstream
program monitor
Writing Operation:- Keyboard Program
ofstream Buffer HDD
Input Output Hierarchy of input output system
AimPoint InfoSystem Pvt. Ltd ,239 “sunny” Place II Floor MP Nagar Zone - 1
Ph. No : 9425007241,9425302400,4064253
2
File Modes(manipulators)
ios::in :- Open existing file only in reading
mode
ios::out :- Open existing file or create new file in
writing mode, if file exist then the all
content of this file get destroyed in
this mode.
ios::app :- Open existing or create new file in
append mode.
ios::ate :- Open existing or create new file in
append mode with allowed updation.
ios::binary :- Open existing or create new file in
binary mode
More then one mode :
ios::in | ios::out | ios::binary
FUNCTIONS DETAIL :-
1)open() :it‟s a member function of „ifstream‟ class ,which is used to open a file in „ios::in‟ mode.
2)open() :it‟s a member function of „ofstream‟ class ,which is used to open a file in „ios::out‟
mode.
3)close() :it‟s a member function of „filebuf‟ class ,which is used to close file into secondary
memory
4)fail() : it‟s a member function of „ios‟ class , return „nonzero‟if file is not opened ,otherwise
return „zero‟.
5)eof() : it‟s a member function of „ios‟ class, return „nonzero‟if EOF(end of file) is encountered
, otherwise return „zero‟.
6)get() : it‟s a member function of „ifstream‟ class,which is used to read single character from
file.
7)put() : it‟s a member function of „ofstream‟ class,which is used to write single character into
file.
#1.WAP to write n integers in a file :
#include<fstream.h>
#include<iostream.h>
void main( )
{ int no,n,i;
ofstream fout;
fout.open(“Num”) ;
Or
ofstream fout(“Num”) ;
cout<<”How many no.s do you want to enter”;
cin>>n;
for( i=1; i<=n ; i++ )
{ cin>>no ;
fout<<no<<” “ ;
}
fout.close( );
}
AimPoint InfoSystem Pvt. Ltd ,239 “sunny” Place II Floor MP Nagar Zone - 1
Ph. No : 9425007241,9425302400,4064253
3
#2.WAP to read integer from a file :
#include<fstream.h>
#include<iostream.h>
void main( )
{int no ;
ifstream fin ;
fin.open(“Num”);
or
ifstream fin(“Num”);
if( fin.fail( ) )
{ cout<<”File not found”;
return;
}
while( !fin.eof( ) )
{ fin>>no;
cout<<” ”<<no;
}
fin.close();
}
#3.WAP to display the contents of any text file,where file name is given by user :
#include<fstream.h>
#include<iostream.h>
void main( )
{ char ch,fname[20];
cout<<”Enter file name or path”;
gets(fname); // I/P :matrix.cpp
ifstream fin(fname);
if( fin.fail( ) )
{ cout<<”File not found”;
return;
}
while( !fin.eof( ) )
{ ch=fin.get();
cout<<ch;
}
fin.close();
}
#4.WAP to copy one file into another file where source file & target file name given by
user :
#include<fstream.h>
#include<iostream.h>
void main()
{ char ch , tname[20] , sname[20] ;
cout<<”Enter source file name or path”;
gets(sname);
ifstream fin(sname);
AimPoint InfoSystem Pvt. Ltd ,239 “sunny” Place II Floor MP Nagar Zone - 1
Ph. No : 9425007241,9425302400,4064253
4
if( fin.fail() )
{ cout<<”Source File not found”;
return;
}
cout<<”Enter target file name or path”;
gets(tname);
ofstream fout(tname);
while( !fin.eof( ) )
{ ch=fin.get();
fout.put(ch);
}
cout<<”File copied”;
fin.close();
fout.close();
}
ASSIGNMENTS :
1)WAP to open any file and count no. of Alpha,no. of Upper case char, no. of lower case
char,digit char,punctuation char.
2)WAP to convert upper case file into lower case file.
3)WAP to concat 2 files into third file.
4)WAP to encrypt any text file.
5)WAP to decrypt any text file.
#5.WAP to creat formatted file :
#include<fstream.h>
#include<iostream.h>
void main()
{ char rname[20];
int rno,n,i;
float price;
ofstream fout(“Comp”);
cout<<”How many records do you want to enter”;
cin>>n;
for( i=1 ; i<=n ; i++)
{ cout<<”Enter rno,rname &price”;
cin>>rno>>rname>>price;
fout<<”\n”<<rno<<” “<<rname<<” “<<price;
//space must between values
}
fout.close();
}
AimPoint InfoSystem Pvt. Ltd ,239 “sunny” Place II Floor MP Nagar Zone - 1
Ph. No : 9425007241,9425302400,4064253
5
#6.WAP to read formatted file :
#include<fstream.h>
#include<iostream.h>
void main()
{char rname[20];
int rno;
float price;
ifstream fin(“Comp”);
if( fin.fail() )
{ cout<<”File not found”;
return;
}
while( !fin.eof() )
{ fin>> rno >> rname >> price;
cout<<”\n”<<rno<<” “<<rname<<” “<<price;
}
fin.close();
}
ASSIGNMENTS:
1 ) create a file (name “country”,ios::out) and write some countries name
“Country”
India
Shri lanka
USA
Japan
Australia
Afganistan
2)open “country” file in reading mode(ios::in) and “capital” file in writing mode (ios::out) and write
capital name accordingly “country” file .
“Capital”
Delhi Input format
Columbo “Enter capital of India : Delhi
Washington
Tokyo “Enter capital of Shri lanka : Columbo
Melberne
Kabul “Enter capital of USA : Washington
3) ) open “country” and “capital” file in reading mode(ios::in) and display corresponding capital
“Enter country name:Australia
Capital is:Melberne
FILE POINTER IN C++ :
1)‟get‟/‟read‟ pointer :- It‟s a file pointer which is used to „read‟ data from existing file.
2)‟put‟/‟write‟ pointer :- It‟s a file pointer which is used to „write‟ data into open file.
AimPoint InfoSystem Pvt. Ltd ,239 “sunny” Place II Floor MP Nagar Zone - 1
Ph. No : 9425007241,9425302400,4064253
6
FILE POINTER MOVEMENT IN C++ :
1)seekg( ) :- : it‟s a member function of „istream‟ class,which is used to set the position of „get‟
pointer into file.
Syntex : seekg(no of bytes , position)
if no of bytes is positive ( forword by )
if no of bytes is negative ( backword by)
a) seekg(o,ios::beg) : Go to the starting.
b) seekg(m,ios::beg): move (m+1)th byte from
starting
c) seekg(m,ios::cur): move forward by m th byte
from current position.
d)seekg(-m,ios::cur): move backward by m th
byte from current position.
e)seekg(o,ios::end) : goto the end of file.
f)seekg(-m,ios::end):move backward by m th
byte from end of file.
2)seekp( ) :- : it‟s a member function of „ostream‟ class,which is used to set the position of „put‟
pointer into open file.
Syntex seekp(no of bytes , position)
if no of bytes is positive ( forword by )
if no of bytes is negative ( backword by)
a)seekp(o,ios::beg): Go to the starting.
b)seekp(m,ios::beg): move (m+1)th byte from
starting
c)seekp(m,ios::cur): move forward by m th byte
from current position.
d)seekp(-m,ios::cur):move backward by m th
byte from current position.
e)seekp(o,ios::end) : goto the end of file.
f)seekp(-m,ios::end):move backward by m th
byte from end of file.
3)tellg( ) :- : it‟s a member function of „istream‟ class,which is used to return the current position
of „get‟ pointer in bytes.
int pos;
pos=fin.tellg( );
4)tellp( ) :- it‟s a member function of „ostream‟ class,which is used to return the current
position of „put‟ pointer in bytes.
int pos;
pos=fout.tellp( );
5)remove( ) :- it‟s a function of <stdio.h> header file,which is used to remove file from
secondary
memory(HDD).
Syntex : remove(“file name or path”);
AimPoint InfoSystem Pvt. Ltd ,239 “sunny” Place II Floor MP Nagar Zone - 1
Ph. No : 9425007241,9425302400,4064253
7
6)rename( ) :- it‟s a function of <stdio.h> header file,which is used to rename file from one
name to another name.
Syntex :
rename(“source file name”,“target file name ”);
6) read( ): member fn of “isteram” class which is used to read structured data(structure/class)
from existing file
syntax : read( ( char*) &obj,sizeof(obj) );
7)write( ): member fn of “osteram” class which is used to write structured data(structure/class)
into open file
syntax : write( ( char*) &obj,sizeof(obj) );
MENU DRIVEN PROGRAME ON FILE HANDLING :
class Record
{ char rname[20];
int rno;
float price;
public:
void get( )
{ cout<<”Enter rno,rname &price”;
cin>>rno>>rname>>price;
}
void show( )
{ cout<<”\n”<<rno<<” “<<rname<<” “<<price;
}
void append( )
{ fstream ff;
ff.open(“comp”,ios::app);
ff.writw((char*)this , sizeof(Record) );
ff.close( );
}
void traverse( )
{ Record t;
ifstream fin(“Comp”);
if(fin.fail( ))
{ cout<<”File not found”;
return;
}
while( !fin.eof( ) )
{ fin.read((char*)&t ,sizeof(t));
t.show( );
}
fin.close( );
}
AimPoint InfoSystem Pvt. Ltd ,239 “sunny” Place II Floor MP Nagar Zone - 1
Ph. No : 9425007241,9425302400,4064253
8
void search( )
{ Record t;
ifstream fin(“Comp”);
if(fin.fail())
{ cout<<”File not found”;
return;
}
int val;
cout<<”Enter searching element”;
cin>>val;
while(!fin.eof( ))
{ fin.read((char*)&t,sizeof(t));
if( t.rno == val )
{ cout<<”Found”;
t.show( );
fin.close( );
return;
}//end of if
} //end of while loop
cout<<”Record not found”;
fin.close( );
}
void insert( ) Insertion procedure in file
{ Record t, i ; Step 1 : open original file in reading mode(ios::in)
ifstream fin(“Comp”); and temporary file in writing mode (ios::out)
Step 2 : copy all the records from original file into
ofstream fout(“temp”);
temporary file upto the record ,after which
if(fin.fail( )) we want to insert a new record
{ cout<<”File not found”; step 3 : write inserted record in temporary file .
return; step 4 : copy remaining records from original file
} into temporary file .
int val,flag=0 ; step 5 : close both files in HDD .
cout<<”Enter no after which you want to insert element”; step 6 : remove original file , and rename
“temporary file name” to “original file name “
cin>>val;
while( fin.read((char*)&t,sizeof(t) )
{ fout.write((char*)&t,sizeof(t) );
if( t.rno == val )
{ cout<<”Enter new record”;
i.get( );
fout.write((char*)&i,sizeof(i));
cout<<”Record inserted”;
flag=1;
}
}//end of while
if(flag= =0)
cout<<”\nRecord Not Found “ ;
fin.close( );
fout.close( );
remove(“Comp”);
rename(“temp”,”Comp”);
}
AimPoint InfoSystem Pvt. Ltd ,239 “sunny” Place II Floor MP Nagar Zone - 1
Ph. No : 9425007241,9425302400,4064253
9
void delete( ) Deletion procedure in file
{ Record t; Step 1 : open original file in reading
int flag=0,val; mode(ios::in) and temporary file in
writing mode (ios::out)
ifstream fin(“Comp”); Step 2 : copy all the records from original file
ofstream fout(“Temp”); into temporary file except the the
if(fin.fail( )) record , which we want to delete .
{ cout<<”File not found”; step 3 : close both files in HDD .
return; step 4 : remove original file , and rename
} “temporary file name” to “original file name “
cout<<”Enter no to be deleted”;
cin>>val;
while(fin.read((char*)&t,sizeof(t))
{ if(t.rno != val )
fout.write((char*)&t,sizeof(t));
else
flag=1;
}
if(flag==0)
cout<<”Record not found”;
fin.close( );
fout.close( );
remove(“Comp”);
rename(“Temp”,”Comp”);
}
void update( )
{ fstream ff(“Comp”,ios::in | ios::out);; Updation procedure in file
Step 1 : open original file in reading mode(ios::in) and in
int val,c=0,pos; writing mode (ios::out), so we can perform reading as
if(ff.fail( )) well as writing operation
{ cout<<”File not found”; Step 2 : first read one by one record in file by READ
return; pointer upto the record ,which we want to update
} step 3 : Move WRITE pointer into file up to the record
cout<<”Enter rno to be updated”; to be updated
cin>>val; step 4 : perform updation operation in object and over
write into file .
Record t ; step 5 : close file .
while( ff.read((char*)&t,sizeof(t) )
{ if(t.rno==val)
{ pos=(c*sizeof(t));
ff.seekp(pos,ios::beg);
cout<<”Enter new price”;
cin>>t.price;
ff.write((char*)&t,sizeof(t));
cout<<”Record updated”;
flag=1;
}
c++;
}//end of while
if(flag==0)
cout<<”Record not found”;
ff.close( );
}
AimPoint InfoSystem Pvt. Ltd ,239 “sunny” Place II Floor MP Nagar Zone - 1
Ph. No : 9425007241,9425302400,4064253
10
void sort( ) Sorting procedure in file
{ Record *p,t; Step 1 : open original file in reading mode(ios::in) .
int i=0,j; Step 2 : count no of records in file .
ifstream fin(“Comp”); step 3 : create dynamic array ( for no of records ) on
int nor; pointer
step 4 : copy complete file in dynamic array
fin.seekg(o,ios::end); step 5 : perform sorting operation in this array
nor=fin.tellg( ) / sizeof(t) ; step 6 : display this sorted dynamic array / copy this
p=new Record[nor]; sorted dynamic array into another file
fin.seekg(o,ios::beg); step 7 : close file
while(fin.read((char*)&t,sizeof(t))
p[i++]=t;
for( i=0 ; i<nor-1 ; i++ )
{ for(j=i+1 ; j<nor ; j++)
{ if(p[j].price<p[i].price)
{
t = p[ j ];
p[ j ]=p[ i ];
p[ I ]=t;
}
}
}
cout<<”Sorted file is”;
for( i=0 ; i<nor ; i++)
p[i].show( );
fin.close( );
delete[ ]p;
}
};//end of the class
void main( )
{ Record i1;
int ch;
do
{
cout<<”\n1 Append”;
cout<<”\n2 Traverse”;
cout<<”\n3 Search”;
cout<<”\n4 Insert”;
cout<<”\n5 Delete”;
cout<<”\n6 Update”;
cout<<”\n7 Sort”;
cout<<”\n 0 exit”;
cout<<”\nEnter your choice”;
cin>>ch;
AimPoint InfoSystem Pvt. Ltd ,239 “sunny” Place II Floor MP Nagar Zone - 1
Ph. No : 9425007241,9425302400,4064253
11
switch(ch)
{
case 1: i1.get( );
i1.append( );
break;
case 2: i1.traverse( );
break;
case 3: i1.search( );
break;
case 4: i1.insert( );
break;
case 5: i1.delete( );
break;
case 6: i1.update( );
break;
case 7: i1.sort( );
break;
case 0: break;
default : cout<<”\n Invalid Choice “;
}//end of switch
}while( ch != 0 );
}
// end of file handling//
AimPoint InfoSystem Pvt. Ltd ,239 “sunny” Place II Floor MP Nagar Zone - 1
Ph. No : 9425007241,9425302400,4064253