File Handling is used in C language for store a data permanently in computer.
Using file handling you can store your data in Hard disk.
http://www.tutorial4us.com/cprogramming/c-file-handling
2. FileFile
A file is a collection of related data stored inA file is a collection of related data stored in
a particular area on the disk . The data isa particular area on the disk . The data is
stored in disk using the concept of file .stored in disk using the concept of file .
File Handling in C++File Handling in C++
Tutorial4us.comTutorial4us.com
3. Why FileWhy File
Permanent storage of data : -Permanent storage of data : - (all the message(all the message
or value printed with help of any outputor value printed with help of any output
statements like printf , putchar are neverstatements like printf , putchar are never
available for future use ) .available for future use ) .
If there is a large amount of data generated asIf there is a large amount of data generated as
output by a program, storing that output in fileoutput by a program, storing that output in file
will help in easy handling /analysis of thewill help in easy handling /analysis of the
output , as user can see the whole output at anyoutput , as user can see the whole output at any
time even after complete execution of thetime even after complete execution of the
program.program.
Tutorial4us.comTutorial4us.com
4. If we need lot of data to be inputted, user cannotIf we need lot of data to be inputted, user cannot
keep on typing that again and again for repeatedkeep on typing that again and again for repeated
execution of program. In that case, all input dataexecution of program. In that case, all input data
can be once written in a file and then that filecan be once written in a file and then that file
can be easily used as the input file.can be easily used as the input file.
The transfer of input – data or output – data fromThe transfer of input – data or output – data from
one computer to another can be easily done byone computer to another can be easily done by
using files.using files.
Tutorial4us.comTutorial4us.com
5. Stream classesStream classes
Filebuf :-Filebuf :- its purpose is to set the file buffer to read andits purpose is to set the file buffer to read and
write . Containwrite . Contain openprotopenprot constant used in theconstant used in the open()open()
of file stream classes . Also containof file stream classes . Also contain close()close() andand open()open()
as method.as method.
Fstreambase :-Fstreambase :- provides operations common to the fileprovides operations common to the file
stream. Serves as a base for fstream, ifstream andstream. Serves as a base for fstream, ifstream and
ofsteram class. Containsofsteram class. Contains open()open() andand close()close() functionfunction
Ifstream :-Ifstream :- provides input operations. Contains open()provides input operations. Contains open()
with default input mode. Inherits the functionswith default input mode. Inherits the functions get()get(),,
getline()getline(),, read()read(),, seekg()seekg() andand tellg()tellg() function fromfunction from
istream.istream.
Tutorial4us.comTutorial4us.com
6. OfstreamOfstream :-:- provides output operations.provides output operations.
ContainsContains open()open() with default output mode.with default output mode.
InheritsInherits put()put(),, seekp()seekp(),, teelp()teelp() andand write()write()
function from ostream.function from ostream.
Fsream :-Fsream :- provides support for simultaneousprovides support for simultaneous
input and output operations. Containsinput and output operations. Contains open()open()
with default input mode. Inherits all the functionwith default input mode. Inherits all the function
fromfrom isteramisteram and ostream classes throughand ostream classes through
iostreamiostream
Tutorial4us.comTutorial4us.com
7. Opening file using open()Opening file using open()
The functionThe function open()open() can be used to opencan be used to open
multiple files that use the same stream object.multiple files that use the same stream object.
file-stream-class stream-object;file-stream-class stream-object;
stream-object . open (“filename”);stream-object . open (“filename”);
Tutorial4us.comTutorial4us.com
8. Open and close a fileOpen and close a file
eg:-eg:-
ofstream outfile; // create streamofstream outfile; // create stream
outfile . open (“DATA1”); // connect stream to DATA1outfile . open (“DATA1”); // connect stream to DATA1
…………………………………………………………....
…………………………………………………………....
outfile . Close(); //disconnect stream from DATA1outfile . Close(); //disconnect stream from DATA1
outfile . Open(“DATA2”); //connect stream to DATA2outfile . Open(“DATA2”); //connect stream to DATA2
…………………………………………………………....
…………………………………………………………....
outfile . close();outfile . close();
…………………………………………………………....
Tutorial4us.comTutorial4us.com
9. Mode of file openingMode of file opening
ios :: out = open file for write onlyios :: out = open file for write only
ios :: in = open file for read onlyios :: in = open file for read only
ios :: app = append to end-of-fileios :: app = append to end-of-file
ios :: ate = take us to the end of the file when itios :: ate = take us to the end of the file when it
is openedis opened
Both ios :: app and ios :: ate take us to the end of the fileBoth ios :: app and ios :: ate take us to the end of the file
when it is opened. The difference between the twowhen it is opened. The difference between the two
parameters is that the ios :: app allows us to add data toparameters is that the ios :: app allows us to add data to
the end of file only, while ios :: ate mode permits us to addthe end of file only, while ios :: ate mode permits us to add
data or to modify the existing data any where in the file.data or to modify the existing data any where in the file.
Tutorial4us.comTutorial4us.com
10. The mode can combine two or more parametersThe mode can combine two or more parameters
using the bitwiseusing the bitwise OROR operator (symbol |)operator (symbol |)
eg :-eg :-
fstream file;fstream file;
file . Open(“ data . txt”, ios :: out | ios :: in);file . Open(“ data . txt”, ios :: out | ios :: in);
Tutorial4us.comTutorial4us.com
11. File pointerFile pointer
Each file have two associated pointers known asEach file have two associated pointers known as
the file pointers. One of them is called the inputthe file pointers. One of them is called the input
pointer (or get pointer) and the other is called thepointer (or get pointer) and the other is called the
output pointer (or put pointer). The input pointeroutput pointer (or put pointer). The input pointer
is used for reading the contents of a given fileis used for reading the contents of a given file
location and the output pointer is used for writinglocation and the output pointer is used for writing
to a given file location.to a given file location.
Tutorial4us.comTutorial4us.com
12. Function for manipulationFunction for manipulation
of file pointerof file pointer
When we want to move file pointer to desiredWhen we want to move file pointer to desired
position then use these function for manage theposition then use these function for manage the
file pointers.file pointers.
Seekg () = moves get pointer (input) to aSeekg () = moves get pointer (input) to a
specified locationspecified location
Seekp () = moves put pointer (output) to aSeekp () = moves put pointer (output) to a
specified locationspecified location
tellg () = gives the current position of the get pointertellg () = gives the current position of the get pointer
tellp () = gives the current position of the put pointertellp () = gives the current position of the put pointer
Tutorial4us.comTutorial4us.com
13. fout . seekg(0, ios :: beg) -- go to startfout . seekg(0, ios :: beg) -- go to start
fout . seekg(0, ios :: cur) -- stay at current positionfout . seekg(0, ios :: cur) -- stay at current position
fout . seekg(0, ios :: end) -- go to the end of filefout . seekg(0, ios :: end) -- go to the end of file
fout . seekg(m, ios :: beg) -- move to m+1 byte in the filefout . seekg(m, ios :: beg) -- move to m+1 byte in the file
fout . seekg(m, ios :: cur) -- go forward by m bytes fromfout . seekg(m, ios :: cur) -- go forward by m bytes from
the current positionthe current position
fout . seekg(-m, ios :: cur) -- go backward by m bytesfout . seekg(-m, ios :: cur) -- go backward by m bytes
from the current positionfrom the current position
fout . seekg(-m, ios :: end) -- go backward by m bytesfout . seekg(-m, ios :: end) -- go backward by m bytes
from the endfrom the end
Tutorial4us.comTutorial4us.com
14. put() and get() functionput() and get() function
The function put() write a single character to theThe function put() write a single character to the
associated stream. Similarly, the function get()associated stream. Similarly, the function get()
reads a single character from the associatedreads a single character from the associated
stream.stream.
Tutorial4us.comTutorial4us.com
15. read() and write() functionread() and write() function
file . read ((char *)&V , sizeof (V));file . read ((char *)&V , sizeof (V));
file . Write ((char *)&V , sizeof (V));file . Write ((char *)&V , sizeof (V));
These function take two arguments. The first isThese function take two arguments. The first is
the address of the variable V , and the second isthe address of the variable V , and the second is
the length of that variable in bytes . The addressthe length of that variable in bytes . The address
of variable must be cast to type char * (i.e pointerof variable must be cast to type char * (i.e pointer
to character type) .to character type) .
Tutorial4us.comTutorial4us.com
16. Program for file handlingProgram for file handling
#include< iostream . h>#include< iostream . h>
#include< conio .h>#include< conio .h>
#include< fstream . h>#include< fstream . h>
Class studentClass student
{{
Public:Public:
Struct stuStruct stu
{{
char name[20];char name[20];
int roll;int roll;
}s;}s;
Void put_data();Void put_data();
Void get_data();Void get_data();
};}; Tutorial4us.comTutorial4us.com
17. void student :: put_data()void student :: put_data()
{{
cout<<"enter name ";cout<<"enter name ";
cin>>s. name;cin>>s. name;
cout<<"enter roll ";cout<<"enter roll ";
cin>>s. roll;cin>>s. roll;
file. Open ("hit. txt“ , ios :: out | ios :: app);file. Open ("hit. txt“ , ios :: out | ios :: app);
file. write ((char *)this, sizeof (student));file. write ((char *)this, sizeof (student));
file. close();file. close();
getch();getch();
get_data();get_data();
}}
Tutorial4us.comTutorial4us.com
18. void student :: get_data()void student :: get_data()
{{
int temp;int temp;
cout<<"enter roll no. ";cout<<"enter roll no. ";
cin >>temp;cin >>temp;
fstream file;fstream file;
file. open ("hit . txt", ios :: in);file. open ("hit . txt", ios :: in);
file.seekg(0,ios::beg);file.seekg(0,ios::beg);
While (file . read ((char *) this, sizeof (student)))While (file . read ((char *) this, sizeof (student)))
{{
If (temp==s. roll)If (temp==s. roll)
{{
cout<<"student name "<< s . name<<"n";cout<<"student name "<< s . name<<"n";
cout<<"student roll "<< s . roll;cout<<"student roll "<< s . roll;
}}
}}
getch ();getch (); Tutorial4us.comTutorial4us.com