Professional Documents
Culture Documents
----------------------
File handling is used for store a data permanently in computer. Using file handling we can store our data
in secondary memory (Hard disk).
Naming a file
Opening a file
Writing data into the file
Reading data from the file
Closing a file.
Streams in C++
We give input to the executing program and the execution program gives back the output. The sequence
of bytes given as input to the executing program and the sequence of bytes that comes as output from the
executing program are called stream. In other words, streams are nothing but the flow of data in a
sequence of bytes.
Keyboard Monitor
RAM
Output Stream(ofstream)
Stud.doc FILE
ios
iostream file
iostream
-----------------------------------------------------------------------------------------------------------------------------------
fstream file
fstreambase
ios
This class is the base class for other classes in this class hierarchy.
This class contains the necessary facilities that are used by all the other derived classes for
input and output operations.
istream
This class is derived from the class ‘ios’.
This class handle input stream.
The extraction operator(>>) is overloaded in this class to handle input streams from files to
the program execution.
This class declares input functions such as get(), getline() and read().
ostream
This class is derived from the class ‘ios’.
This class handle output stream.
The insertion operator(<<) is overloaded in this class to handle output streams to files from
the program execution.
This class declares output functions such as put() and write().
streambuf
This class contains a pointer which points to the buffer which is used to manage the input
and output streams.
fstreambase
This class provides operations common to the file streams. Serves as a base for fstream,
ifstream and ofstream class.
This class contains open() and close() function.
ifstream
This class provides input operations.
It contains open() function with default input mode.
Inherits the functions get(), getline(), read(), seekg() and tellg() functions from the istream.
ofstream
This class provides output operations.
It contains open() function with default output mode.
Inherits the functions put(), write(), seekp() and tellp() functions from the ostream.
fstream
This class provides support for simultaneous input and output operations.
Inherits all the functions from istream and ostream classes through iostream.
filebuf
Its purpose is to set the file buffers to read and write.
Opening and closing a File
------------------------------------------
If we want to use a disk file, we need to decide the following things about the file and its intended
use:
1. Suitable name for the file
2. Data type and structure
3. Purpose
4. Opening method
The file name is a string of characters that make up a valid file name for the operating system. It
may contain two parts, a primary name and an optional period with extension.
Eg:
Student.doc
Item.txt
For opening a file, we must first create a file stream and then link it to the file name. A file stream
can be defined using the class’s ifstream, ofstream and fstream. The class to be used depends upon
the purpose i.e. whether we want to read data from the file or write data to it.
Note: The first method is useful when we use only one file in the stream. The second method is used
when we want to manage multiple files using one stream.
1. Create a file stream object to manage the stream using the appropriate class. That is the
class ofstream is used to create the output stream and the class ifstream is used to create
input stream.
2. Initialize the file object with the desired file name
Eg:
File_stream_class <stream-object>(“file-name”);
ofstream fout(“student.doc”);
This create “fout” as an ofstream object that manages the output stream. The object can be
any valid C++ name such as o_file, myfile, outfile etc. This statement opens the file
“student.doc” and attaches it to the output stream “fout”.
Similarly, the following statements declares “fin” as an ifstream object and attaches it to the
file “student.doc” for reading.
Eg:
ifstream fin(“student.doc”);
The connection with a file is closed automatically when the stream object expires mean when the
program terminates.
Q: WA C++ file handling program to write data into the file called student.doc
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"Enter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
ofstream fout("d:/student.doc");
fout.close();
return 0;
}
Q: WA C++ file handling program to read data from the file called student.doc
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
ifstream fin("d:/student.doc");
fin.close();
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
return 0;
}
Q: write a single file handling program in c++ to reading and writing data on a file.
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"Enter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
ofstream fout("d:/student.doc");
fout.close();
ifstream fin("d:/student.doc");
fin.close();
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
return 0;
}
Opening file using member function open()
---------------------------------------------------------
The function open() can be used to open multiple files that use the same stream object.
Syntax:
file_stream_class <stream-object>;
stream-object.open(“file-name”);
Q: WA C++ program to write data into the file called student.doc using member function open().
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"Enter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
ofstream fout;
fout.open("d:/student.doc");
fout.close();
return 0;
}
Q: WA C++ program to read data from the file called student.doc using member function open().
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
ifstream fin;
fin.open("d:/student.doc");
fin.close();
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
return 0;
}
Q: write a single program in c++ to reading and writing data on a file using member function
open().
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"Enter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
ofstream fout;
fout.open("d:/student.doc");
fout.close();
ifstream fin;
fin.open("d:/student.doc");
fin>>rno>>name>>fee; //read data from the file student
fin.close();
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
return 0;
}
The function open() can be used to open multiple files that use the same stream object.
Q: Write a C++ program to open multiple files for writing and reading purpose. Use open()
function.
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
int eid,salary;
char ename[50];
ofstream fout;
fout.open("d:/student.doc");
fout<<rno<<"\t"<<name<<"\t"<<fee; //write data to the file student
fout.close();
fout.open("d:/employee.doc");
fout<<eid<<"\t"<<ename<<"\t"<<salary;
fout.close();
ifstream fin;
fin.open("d:/student.doc");
fin>>rno>>name>>fee; //read data from the file student
fin.close();
cout<<endl<<"Roll-NO\tName\tFee";
cout<<endl<<endl<<"-----------------------------";
cout<<endl<<endl<<rno<<"\t"<<name<<"\t"<<fee;
fin.open("d:/employee.doc");
fin>>eid>>ename>>salary; //read data from the file student
fin.close();
cout<<endl<<endl<<"EMP-ID\tName\tSalary";
cout<<endl<<"-----------------------------";
cout<<endl<<endl<<eid<<"\t"<<ename<<"\t"<<salary;
return 0;
}
File Opening modes
---------------------------
We have used “ifstream” and “ofstream” constructor and member function open() to create new files as
well as to open the existing files. In both these methods, we used to only one argument that was the file-
name.
However these functions can take two arguments, the first argument is file-name and second argument for
specifying the file-mode.
Syntax :
stream-object.open(“file-name”, mode);
The second argument “mode” called file mode parameter specifies the purpose for which the file is
opened.
The prototype of these class member functions contains default values for the second argument and
therefore they use the default values in the absence of the actual values.
Note:
1. Opening a file in ios::out mode also open it in the ios::trunc mode by default.
2. Both ios::app and ios::ate take us to the end the file when it is opened. The difference between the
two parameters is that the ios::app allows to add data to the end of the file only, while ios::ate
mode permits us to add data or to modify existing data anywhere in the file. In both the cases, a
file is created by the specified name, if it does not exist.
3. Creating a stream using ifstream implies input and creating a stream using ofstream implies
output. So in these cases it is not necessary to provide the mode parameter.
4. The fstream class does not provide a mode by default and therefore, we must provide the mode
explicitly when using an object of fstream class.
5. The mode can combine two or more parameters using the bitwise OR operator.
Eg:
Q: WA C++ program to read and write from the file called student.doc. Use fstream class and
member function open() .
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"\nEnter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
fstream file;
file.open("d:/student.doc",ios::out);
file<<rno<<"\t"<<name<<"\t"<<fee; //write data to the file student
file.close();
file.open("d:/student.doc",ios::in);
file>>rno>>name>>fee; //read data from the file student
file.close();
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
return 0;
}
The !(logical negation operator) is useful for detecting the errors. It is a unary operator and in short it is
called as not operator. The not operator can be used with object of stream class. This operator returns non-
zero value if stream errors are found during operation.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
int rno,fee;
char name[50];
char fname[50];
fstream file;
file.open(fname,ios::in);
if(!file)
{
cout<<"\nError in opening file:\t"<<fname;
getch();
}
file.close();
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
return 0;
}
To avoid this, it is necessary to provide correct instruction to the program that detects the end of file. Thus
the end of file is detected; the process of reading data can be easily terminated.
The eof() member function is used for this purpose. The eof() stands for end of file. The eof() function
returns non-zero value when end of file is detected, otherwise zero.
Q: Write a C++ program to read and display the content of file. Use eof() member function.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char ch;
fstream file;
file.open("d:/student.doc",ios::in);
if(!file)
{
cout<<"\nError in opening file:\t"<<"student.doc";
getch();
}
while(file.eof()==0)
{ // function get() reads a single character from the associated stream.
file.get(ch); // or ch=file.get();
cout<<ch;
}
file.close();
return 0;
}
Write a program to detect end of the file using function eof(). Display the values returned by the
eof()function.
Q: Write a C++ program to count the number of words and lines in a file.
#include<iostream>
#include<fstream>
using namespace std;
main()
{
char str[100];
ifstream fin;
fin.open("e:/str.doc");
if(!fin)
{
cout<<"File Not Found/Opened";
return 0;
}
char ch;
int word=0,line=0;
fin.seekg(0,ios::beg);
while(fin.eof()==0)
{
ch=fin.get();
if(ch==' ')
word++;
if(ch=='\n')
line++;
cout<<ch;
}
cout<<"\nTotal Word:"<<word;
cout<<"\nTotal Line:"<<line;
fin.close();
return 0;
}
Q: Write a C++ program to count the number of alphabets, digit and spaces present in a file.
#include<iostream>
#include<fstream>
using namespace std;
main()
{
char str[100];
cout<<"Enter the String:";
gets(str);
ofstream fout;
fout.open("e:/str1.doc");
int i;
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("e:/str1.doc");
if(!fin)
{
cout<<"File Not Found/Opened";
return 0;
}
char ch;
int a=0,d=0,s=0;
fin.seekg(0,ios::beg);
while(fin.eof()==0)
{
ch=fin.get();
i=ch;
if((i>=65 && i<=90)||(i>=97 && i<122))
a++;
if(i>=47 && i<=58)
d++;
if(ch==' ')
s++;
cout<<ch;
}
cout<<endl<<"No. OF Alphabates:"<<a;
cout<<endl<<"No. Of Digits:"<<d;
cout<<endl<<"No. Of Spaces:"<<s;
fin.close();
return 0;
}
Q: Write a C++ program to read data from a text file and then write in another text file.
int main()
{
ofstream fout(“sare1.txt”); //create a file to write
ifstream fin(“sare1.txt”);
fout<<“Hello India”;
fout.close(); //closing the file
return 0;
}
Default Action
--------------------
When we open a file in read only mode, the input pointer is automatically set at the beginning so that we
can read the file from the start.
Similarly when we open a file in write only mode, the existing contents are deleted and the output pointer
is set at beginning.
In case, we want to open an existing file to add more data, the file is opened in append mode. This moves
the output pointer to the end of the file.
“Demo” file
Manjeet kumar
seekg() This function moves the “get” pointer to a specified location to do a read operation.
tellg() This function tells the current position of the “get” pointer in the file.
seekp() This function moves the “put” pointer to a specified location to do a write operation.
tellp() This function tells the current position of the “put” pointer in the file.
Eg:
ifstream fin(“temp.doc”);
fin.seekg(10);
The bytes in a file are numbered beginning from zero. Therefore, the pointer will be pointing to the 11th
byte in the file.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc",ios::ate);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("d:/Demo.doc",ios::ate);
while(fin.eof()==0)
{
ch=fin.get();
cout<<ch;
}
fin.close();
return 0;
}
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc",ios::ate);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("d:/Demo.doc",ios::ate);
cout<<endl<<"Number of byte="<<x;
fin.close();
return 0;
On execution of this statement, the input pointer is moved to the end of the file “Demo.doc” and the value
of ‘x’ will represent the number of bytes in the file.
Specify the offset
----------------------
We have seen how to move a file pointer to desired location using the seek function. The argument to
these functions represents the absolute position in the file.
file
Start end
fin.seekg(m);
m bytes
file pointer
“seek” function seekg() and seekp() can also be used with two arguments as follows:
seekg(offset, refposition) ;
seekp(offset, refposition);
The parameter offset represents the number of bytes the file pointer is to be moved from the location
specified by the parameter refposition. The refposition takes one of the following three constants defined
in the “ios” class.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc", ios::in|ios::out|ios::ate|ios::binary);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("d:/Demo.doc");
fin.seekg(7,ios::beg); //move 8 bytes from the beg.
while(fin.eof()==0)
{
ch=fin.get();
cout<<ch;
}
fin.close();
return 0;
}
Q: Write a program to write text in the file. Read the text from the file from end of file. Display the
contents of file in reverse order.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc", ios::out|ios::ate|ios::binary);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("d:/Demo.doc");
fin.seekg(0,ios::end); //move the cursor to the end of file
int m=fin.tellg();
for(i=1;i<=m;i++)
{
fin.seekg(-i,ios::end);
ch=fin.get();
cout<<ch;
}
fin.close();
return 0;
}
Sequential input and output operation
------------------------------------------------
File stream classes support a number of member functions for performing the input and output operations
on files. One pair of functions, put() and get() are designed for handling a single character at a time.
Another pair of functions, write() and read() are designed to write and read blocks of binary data.
The function put() writes a single character to the associated stream. Similarly the function get() reads a
single character from the associated stream.
Example:
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
main()
{
char str[100],ch;
int i;
cout<<"Enter the String:";
cin.getline(str,100);
ofstream fout;
fout.open("d:/Demo.doc", ios::in|ios::out|ios::ate|ios::binary);
for(i=0;str[i]!='\0';i++)
fout.put(str[i]); //put a character to a file
fout.close();
ifstream fin;
fin.open("d:/Demo.doc");
while(fin.eof()==0)
{
ch=fin.get(); //get a character from a file
cout<<ch; //display it on screen
}
fin.close();
return 0;
}
write() and read() functions
----------------------------------
The functions write() and read(), unlike the function put() and get(), handle the data in binary form. This
means that the values are stored in the disk file in the same format in which they are stored in the internal
memory.
Example:
The ‘int’ value 2594 is stored in the binary and character format. The ‘int’ takes two bytes to store its
value in the binary format, irrespective of it’s size. But a 4 digit int value will take 4 bytes to store it in
character format.
2 bytes
Character format 2 5 9 4
4 bytes
The binary format is more accurate for storing the numbers as they are stored in the exact internal
representation. There are no conversions while saving the data and therefore saving is much faster.
The binary input and output functions take the following form:
file.write((char *)&v,sizeof(v));
These functions takes two argument, the first is the address of the variable ‘v’ and the second is the length
of that variable in bytes. The address of the variable must be cast to type char *(i.e. pointer to char).
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int rno,fee;
char name[50];
cout<<"\nEnter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
ofstream fout;
fout.open("d:/student.doc");
fout.write((char*)&rno,sizeof(rno));
fout.write((char*)&name,sizeof(name));
fout.write((char*)&fee,sizeof(fee));
fout.close();
ifstream fin;
fin.open("d:/student.doc");
fin.read((char*)&rno,sizeof(rno));
fin.read((char*)&name,sizeof(name));
fin.read((char*)&fee,sizeof(fee));
fin.close();
cout<<"\nRoll No:\t"<<rno<<endl;
cout<<"\nName:\t"<<name<<endl;
cout<<"\nFee:\t"<<fee<<endl;
return 0;
}
#include<iostream>
#include<fstream>
using namespace std;
class Student
{
int rno,fee;
char name[50];
public:
void set_data()
{
cout<<"\nEnter the Roll Number:";
cin>>rno;
cout<<"\nEnter the Name:";
cin>>name;
cout<<"\nEnter the Fee:";
cin>>fee;
}
void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};
main()
{
int i,no;
Student s[10];
cout<<"\nEnter Number of Student:";
cin>>no;
ofstream fout;
fout.open("d:/Student.doc");
ifstream fin;
fin.open("d:/Student.doc");
if(!fin)
{
cout<<"\nFile not found.";
return 0;
}
for(i=0;i<no;i++)
{
fin.read((char*)&s[i],sizeof(s[i]));
s[i].display();
}
fin.close();
return 0;
}
Q. Create a class to specify data on students given below:
Write a menu driven program in C++ for following operations on student class such as Add,
Display all record, Search record by given roll number and Delete record by given roll number
from the file.
#include<iostream.h>
#include<conio.h>
#include<process.h>
#include<fstream.h>
#include<stdio.h>
void deletedata(int);
void search(int);
class stud
{
public:
int rno;
char name[20];
public:
void getdata()
{
cout<<"\nEnter the rno:";
cin>>rno;
fflush(stdin);
cout<<"Enter the name:";
cin>>name;
}
void display()
{
cout<<endl<<rno<<"\t"<<name<<endl;
}
};
main()
{
int i,chk;
char chk1;
char ch;
stud s;
fstream file,temp;
clrscr();
ofstream fout1;
ifstream fin;
// fout.open("b.dat",ios::in|ios::out|ios::ate|ios::binary);
cout<<"\n1.ADD\n2.DISPLAY CURRENT RECORD\n3.UPDATE
RECORD\n4.DELETE\n5.SEARCH\n6.Exit";
while(1)
{
cout<<"\nEnter the choice";
cin>>chk;
switch(chk)
{
case 1:
fin.open("student.doc");
if(!fin)
{
cout<<"Error in opening file.";
getch();
exit(0);
}
while(fin.read((char*)&s,sizeof(s)))
{
s.display();
}
fin.close();
break;
case 2:
cout<<"\nCURRENT INFORMATION\n";
fin.open("student.doc",ios::in);
while(fin.read((char*)&s,sizeof(s)))
{
s.display();
}
fin.close();
break;
case 3:
ofstream fout;
fout.open("student.doc", ios::in|ios::out|ios::ate|ios::binary);
if(!fout)
{
cout<<"Error in opening file.";
getch();
exit(0);
}
int last=fout.tellp();
int n=last/sizeof(s);
fout.write((char*)&s,sizeof(s));
fout.close();
fin.open("student.doc");
fin.seekg(0);
cout<<"\n CONTENT OF THE UPDATED FILE\n";
while(fin.read((char*)&s,sizeof(s)))
{
s.display();
}
fin.close();
break;
case 4:
int rno1;
cout<<"\nenter the rno to delete the record:";
cin>>rno1;
deletedata(rno1);
break;
case 5:
int rno2;
cout<<"\nEnter the rno to search:";
cin>>rno2;
search(rno2); break;
case 6: exit(0);
getch();
}
return 0;
stud s;
fstream file,temp;
file.open("student.doc",ios::in);
temp.open("temp_student.doc",ios::out);
file.seekg(0);
//while(!file.eof())
//{
while(file.read((char *)&s,sizeof(s)))
{
if(s.rno!=rno1)
temp.write((char *)&s,sizeof(s));
}
file.close();
temp.close();
file.open("student.doc",ios::out);
temp.open("temp_student.doc",ios::in);
temp.seekg(0);
//while(!temp.eof())
//{
while(temp.read((char *)&s,sizeof(s)))
{
//if(temp.eof())
// break;
file.write((char *)&s,sizeof(s));
}
file.close();
temp.close();
}
}
file.close();
}