Data File Handling IN C++
Data File Handling IN C++
Data File Handling IN C++
IN C++
What if a FILE?
A file is a stream of bytes stored on some secondary storage devices.
FILES
INPUT/OUTPUT IN C++
STREAMS
The input/output system of C++ handles file
I/O operations in the same way it handles
console I/O operations.
It uses file stream as an interface between
programs and files.
A stream is defined as the flow of data.
Different kinds of stream are used to represent
different kinds of data flow.
Output stream: The stream which
controls the 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 Stream
Read
data
Extract from
input stream
Disk
File
C++
Program
Write
data
Insert into
output stream
Output Stream
INPUT/OUTPUT IN C++
CLASSES
Each stream is associated with a
particular class which contains
definitions and methods for dealing
with that particular kind of data
These include fstream, ifstream and
ofstream. These classes are defined in
the header file fstream.h. Therefore it
is necessary to include this header file
while writing file programs.
The classes contained in fstream.h
are derived from iostream.h. Thus it is
not necessary to include iostream.h in
our program, if we are using the
header file fstream.h in it.
IOS
ISTREAM
OSTREAM
get ()
getline()
read()
>>
put ()
write()
<<
IOSTREAM
IFSTREAM
OFSTREAM
seekg()
tellg()
open()
>>
seekp()
tellp()
open()
<<
FSTREAM
INPUT/OUTPUT IN C++
CLASSES contd.
The ifstream class contains open() function
with default input mode and inherits the
functions get(), getline(), read(), seekg() and
tellg().
The ofstream class contains open() function
with default output mode and inherits
functions put(), write(), seekp() and tellp()
from ostream.
The fstream class contains open() function
with default input/output mode and inherits
all I/O functions from iostream.h.
TYPES OF DATA
FILES
There are two types of data files in C++: Text files
and Binary files
Text files store the information in ASCII
characters. Each line of text in text files is
terminated by a special character called EOL. In
text files some internal translations take place
while storing data.
Binary files store information in binary format.
There is no EOL character in binary files and no
character translation takes place in binary files.
BINARY FILES
Handling of
new lines
Portability
Storage of
numbers
Text Files
Binary Files
Readability
Not readable
Storage
Accuracy
While reading/writing of
numbers, some conversion
errors may occur.
OPENING
Opening of files can be achieved
in two ways:
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
ios::out
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
moved
any
in using
the file
file
pointer|
Two or be
more
modestocan
belocation
combined
theusing
bitwise
operator
The above program will read a text file abc.txt one word
at a time and display it on the screen.
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.
e.g file.read((char *)&s, sizeof(s));
write() write a block of binary data or writes fixed number of bytes from a
specific memory location to the specified stream.
e.g file.write((char *)&s, sizeof(s));
Note: Both functions take two arguments.
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( ).
void main()
{
ofstream fout(xyz.dat, ios::binary);
student stu;
int n, i=0;
cout<<enter no of records you want
to add to a file;
cin>>n;
while(i<n)
{stu.indata();
fout.write((char*)&stu, sizeof stu);
i++;
}
fout.close();
}
void main()
{
ifstream fin(xyz.dat, ios::binary);
if(!fin)
{cout<<error in opening file;
exit(-1);
}
student stu;
while(!fin.eof())
{
fin.read((char*)&stu, sizeof stu);
stu.outdata();
i++;
}
fin.close();
}
The above program will read the binary file xyz.dat and
display all records stored in it.
#include<fstream.h>
#include<process.h>
class student
{
private:
int rollno;
float total;
public:
void indata()
{ cin>>rollno>>total;}
void outdata()
{cout<<rollno<<total;}
}
{
ofstream fout(xyz.dat, ios::binary| ios::app);
student stu;
int n, i=0;
cout<<enter no of records you want to add
to a file;
cin>>n;
while(i<n)
{stu.indata();
fout.write((char*)&stu, sizeof stu);
i++;
}
fout.close();
}
#include<fstream.h>
#include<process.h>
class student
{
private:
int rollno;
float total;
public:
void indata()
{ cin>>rollno>>total;}
void outdata()
{cout<<rollno<<total;}
Int retroll()
{ return rollno;}
}
{
ifstream fin(xyz.dat,
ios::binary);
ofstream fout(def.dat,
ios::binary);
if(!fin)
{cout<<error in opening file;
exit(-1);
}
student stu;
int roll;
cout<<enter roll no of student
whose record you want to
delete;
cin>>roll;
while(!fin.eof())
{
fin.read((char*)&stu, sizeof stu);
if (stu.retroll() != roll)
{fout.write((char*)&stu, sizeof
stu);
}
}
fin.close();
fout.close();
remove(xyz.dat);
rename(def.dat, xyz.dat);
}
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 reading pointer is set at the beginning of the file.
The default writing pointer is set at the end of the file when the
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.
put pointer specifies the location in a file where the next
write operation will occur.
In other words, these pointers indicate the current positions for
read and write operations, respectively. Each time an input or an
output operation takes place, the pointers automatically advance
sequentially.
It is also possible to read from and write to an arbitrary locations
in the file by moving the file pointer.
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
fin.seekg(0,ios::beg);
Explanation
Moves the file pointer to the beginning of the file
fin.seekg(10,ios::beg)
;
fin.seekg(10,ios::cur);
fin.seekg(10,ios::cur);
Fin.seekg(0,ios::cur);
fin.seekg(10,ios::end);
fin.seekg(0,ios::end);
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 tellp() function is identical to the tellg() function, but it
is identified with the put pointer.
void main()
{
fstream fin(xyz.dat, ios::binary |
ios::ate);
if(!fin)
{cout<<error in opening file;
exit(-1);
}
student stu;
int roll;
cout<<enter roll no of student
whose record you want to modify;
cin>>roll;
{
fin.read((char*)&stu, sizeof
stu);
if (stu.retroll() == roll)
{cout<<enter data to be
modified;
stu.indata();
fin.seekg(-sizeof(stu),
ios::curr);
fin.write((char*)&stu, sizeof
stu);
}
fin.close();
}
The above program will read the binary file xyz.dat and
modify the record of the desired roll number.