Data File Handling in C++
Data File Handling in C++
Data File Handling in C++
C++
What if a FILE?
Files are required to save our data (on a secondary storage device) for
future use, as RAM is not able to hold our data permanently.
DIFFERENCE BETWEEN ARRAYS AND FILES
ARRAYS FILES
Arrays are stored in RAM Files are stored on Hard Disk
Arrays can not be used to share Files can be used to share data between
data between programs. programs.
INPUT/OUTPUT IN C++
STREAMS
The input/output system of C++ handles file I/O Input Stream
operations in the same way it handles console I/O Read Extract from
data input stream
operations.
It uses file stream as an interface between programs
Disk C++
and files. Program
File
A stream is defined as the flow of data.
Different kinds of stream are used to represent Insert into
Write
different kinds of data flow. output stream
data
Output stream: The stream which controls the Output Stream
flow of data from the program to file is called
output stream.
Input stream: The stream which controls the
flow of data from the file to the program is
called input stream.
INPUT/OUTPUT IN C++
CLASSES
Each stream is associated with a particular IOS
class which contains definitions and
ISTREAM OSTREAM
methods for dealing with that particular get () put ()
kind of data getline() write()
read() <<
These include fstream, ifstream and >>
ofstream. These classes are defined in the
header file fstream.h. Therefore it is
IOSTREAM
necessary to include this header file while
writing file programs.
The classes contained in fstream.h are IFSTREAM OFSTREAM
seekg() seekp()
derived from iostream.h. Thus it is not tellg() tellp()
necessary to include iostream.h in our open()
FSTREAM open()
>> <<
program, if we are using the header file
fstream.h in it.
INPUT/OUTPUT IN C++
CLASSES contd….
There are two types of data files in C++: Text files and
Binary files
Using Constructor function: This method is useful when we open only one file in a stream.
To open a file using a constructor fuction we create an object of desired stream and
initialize that object ith the desired file name. For eg. The statement
ofstream fout(“ABC.TXT”);
will create an onject fout of class ofstream, opens the file ABC.TXT and attaches it to the
output stream for writing. Similarly the statement
ifstream fin(“ABC.TXT);
will create an object fin of class ifstream, opens the file “ABC.TXT” and attaches it to the input
stream for reading.
Using open() function: This method is useful when we want to open multiple files using a
single stream. For eg.
ifstream fin; //creates input stream
fin.open(“ABC.TXT”); // associates ABC.TXT to this stream
fin.close(); // closes the file
fin.open(“XYZ.TXT”); // associates the input stream with file XYZ.TXT
CLOSING FILES
The connections with a file are automatically closed when the input
and output stream objects expires ie when they go out of scope.
However we can close the file explicitly by using the close() method:
fin.close();
Closing a file flushes the buffer which means the data remaining in
the buffer of input/output stream is moved to its appropriate place.
For example, when an input files connection is closed, the data is
moved from the input bufferto the program and when an output file
connection is closed the data is moved from the output buffer to the
disk file.
FILE MODES
File modes describes the way in which a file is to be used. The most common file
modes are :
File Modes Exolanation
ios::in Opens file for reading. File pointer is at the beginning of the file
ios::out Opens file for writing. If the file is already created and opened in this
mode all the previous content gets erased from the file.
ios::app Opens file for adding new records. File pointer is at the end of the
file. New records can be added only at the end of the file.
ios::ate Opens the file for both reading and writing. File pointer is at the end
of the file when file is opened in his mode but can be moved to any
location in the file using file pointer methods.
ios::binary Opens file in binary mode. By default the file is opened n text mode.
#include<fstream.h>
void main()
{
ofstream fout(“abc.txt”);
fout<<“ i am creating a new text file\n”;
fout<<“this text file contains alphabets and numbers\n”;
fout.close();
}
The above program will create a text file “abc.txt” and store two
lines in it. You can store as many lines as you want.
A PROGRAM TO READ A TEXT FILE CHRACTER
BY CHARACTER
#include<fstream.h>
void main()
{
ifstream fin(“abc.txt”);
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
}
The above program will read a text file “abc.txt” one character at a
time and display it on the screen.
A PROGRAM TO READ A TEXT FILE WORD BY
WORD
#include<fstream.h>
void main()
{
ifstream fin(“abc.txt”);
char ch[20];
while(!fin.eof())
{
fin>>ch;
cout<<ch;
}
fin.close();
}
The above program will read a text file “abc.txt” one word at a time
and display it on the screen.
A PROGRAM TO READ A TEXT FILE LINE BY
LINE
#include<fstream.h>
void main()
{
ifstream fin(“abc.txt”);
char ch[80];
while(!fin.eof())
{
fin.getline(ch,80,”\n”);
cout<<ch;
}
fin.close();
}
The above program will read a text file “abc.txt” one line at a time
and display it on the screen.
BINARY FILE FUNCTIONS
read()- read a block of binary data or reads a fixed number of bytes from the
specified stream and store in a buffer.
write() – write a block of binary data or writes fixed number of bytes from a
specific memory location to the specified stream.
• The first is the address of variable, and the second is the length of that variable in
bytes. The address of variable must be type cast to type char*(pointer to character
type)
• The data written to a file using write( ) can only be read accurately using read( ).
A PROGRAM TO CREATE A BINARY FILE
void main()
#include<fstream.h> {
class student ofstream fout(“xyz.dat”, ios::binary);
{ student stu;
private: int n, i=0;
int rollno; cout<<“enter no of records you want to
float total; add to a file”;
public: cin>>n;
void indata() while(i<n)
{ cin>>rollno>>total;} {stu.indata();
void outdata() fout.write((char*)&stu, sizeof stu);
{cout<<rollno<<total;} i++;
} }
fout.close();
}
The above program will create a binary file “xyz.dat” and store n
records in it.
A PROGRAM TO READ A BINARY FILE
void main()
#include<fstream.h> {
#include<process.h> ifstream fin(“xyz.dat”, ios::binary);
class student if(!fin)
{ {cout<<“error in opening file”;
private: exit(-1);
int rollno; }
float total; student stu;
public: while(!fin.eof())
void indata() {
{ cin>>rollno>>total;} fin.read((char*)&stu, sizeof stu);
void outdata() stu.outdata();
{cout<<rollno<<total;} i++;
} }
fin.close();
}
The above program will read the binary file “xyz.dat” and display all
records stored in it.
A PROGRAM TO ADD NEW RECORDS TO BINARY FILE
void main()
#include<fstream.h>
{
#include<process.h>
ofstream fout(“xyz.dat”, ios::binary| ios::app);
class student
student stu;
{
int n, i=0;
private:
cout<<“enter no of records you want to add to a
int rollno;
file”;
float total;
cin>>n;
public:
while(i<n)
void indata()
{stu.indata();
{ cin>>rollno>>total;}
fout.write((char*)&stu, sizeof stu);
void outdata()
i++;
{cout<<rollno<<total;}
}
}
fout.close();
}
The above program will add n new records at the end of the binary
file “xyz.dat”.
A PROGRAM TO DELETE A RECORD FROM BINARY FILE
#include<fstream.h>
#include<process.h> void main()
while(!fin.eof())
class student {
{
{ ifstream fin(“xyz.dat”, ios::binary);
fin.read((char*)&stu, sizeof stu);
private: ofstream fout(“def.dat”, ios::binary);
if (stu.retroll() != roll)
int rollno; if(!fin)
{fout.write((char*)&stu, sizeof stu);
float total; {cout<<“error in opening file”;
}
public: exit(-1);
}
void indata() }
fin.close();
{ cin>>rollno>>total;} student stu;
fout.close();
void outdata() int roll;
remove(“xyz.dat”);
{cout<<rollno<<total;} cout<<“enter roll no of student
rename(“def.dat”, “xyz.dat”);
Int retroll() whose record you want to delete”;
}
{ return rollno;} cin>>roll;
}
The above program will read the binary file “xyz.dat” and write the records into the
binary file “def,dat” except the record which we want to delete. Later the old file def.dat
is removed and new file def.dat is renamed as xyz.dat.
FILE POINTERS
All i/o streams objects have, at least, one internal stream pointer.
ifstream, like istream, has a pointer known as the get pointer that points
to the element to be read in the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that
points to the location where the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream.
The default writing pointer is set at the end of the file when the file is
opened in app mode.
FILE POINTERS contd…
There are two types of file pointers. These are:
get pointer – specifies the location in a file where the next read
operation will occur.
The seekg() or the seekp() functions are used to move the get and put
pointers respectively either to an absolute address within the file or to
certain number of bytes from a particular position.
The tellg() and tellp() functions can be used to find out the current
position of the get and put file pointers respectively in a file.
seekg()/seekp() FUNCTIONS
The seekg() member function takes two arguments:
Number of bytes to move. (also called offset)
Reference in the file from which the pointer has to be repositioned. There
are three reference points defined in the ios class:
• ios:beg – the beginning of the file.
• ios:cur – the current position of the file pointer.
• ios:end – the end of the file.
For eg.
ifstream fin(“ABC.TXT”);
fin.seekg(10, ios::beg); // here 10 is the offset and ios::beg is the reference position
If the reference point is not specified, ios::beg reference point is assumed. For
eg.
fin.seekg(50); // here the file pointer is moves ahead 50 bytes from the current
position
seekg()/seekp() FUNCTIONS contd…
Command Explanation
fin.seekg(0,ios::beg); Moves the file pointer to the beginning of the file
fin.seekg(10,ios::beg); Moves the file pointer to 10 bytes from the
beginning of the file
fin.seekg(10,ios::cur); Moves the file pointer to 10 bytes ahead from the current position of
the file
fin.seekg(-10,ios::cur); Moves the file pointer to 10 bytes backward from the current position
of the file
Fin.seekg(0,ios::cur); The file pointer remains at the same position
fin.seekg(-10,ios::end); Moves the file pointer to 10 bytes backward from the end of the file
fin.seekg(0,ios::end); Moves the file pointer to the end of the file
The seekp() function is identical to the seekg() function, but it is identified with the
put pointer.
tellg()/tellp() FUNCTIONS
The tellg() function does not have any arguments. It returns the
current byte position of the get pointer relative to the beginning of
the file.
For example:
Ifstream fin(“ABC.TXT”);
long pos = fin.tellg();
The above command will assign the current position of the get
pointer to the variable pos.
The above program will read the binary file “xyz.dat” and modify
the record of the desired roll number.