Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Data File Handling in C++

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

DATA FILE HANDLING IN

C++
What if a FILE?

A file is a stream of bytes stored on some secondary storage devices.


NEED FOR DATA FILES
 Many real life problems requires handling of large amount of
data.
 Earlier we used arrays to store bulk data.
 The problem with the arrays is that arrays are stored in RAM.
 The data stored in arrays is retained as long as the program is
running. Once the program is over the data stored in the arrays
is also lost.
 To store the data permanently we need files.

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

Difference between Files and Arrays( graduating to files ):

ARRAYS FILES
Arrays are stored in RAM Files are stored on Hard Disk

Data is stored temporarily Data is stored permanently

Arrays have fixed size File can have variable size

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….

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.
DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES

These differ on six main parameters:

TEXT FILES BINARY FILES


Handling of new In text files various character translations are In binary files no such translations are
lines performed such as “\r+\f”(carriage return- performed.
linefeed combination)is converted into “\n”(new
line) while reading from a file and vice-versa
while writing.
Portability Portable: one can easily transfer text file from Non portable: Binary files are
one computer to the other dependent. If the new computer uses
a different internal representation for
values they cannot be transferred.
Storage of In text files when we store numbers they are In a binary file 42.9876 is stored in 4
numbers stored as characters eg if we store a decimal no bytes
42.9876 in a text file it occupies 7 bytes
DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES contd…

Text Files Binary Files


Readability Are readable and thus can be Not readable
easily edited using any word
editor.

Storage Occupy more space due to Occupy less space.


character conversions
Accuracy While reading/writing of Highly accurate for numbers
numbers, some conversion because it stores the exact
errors may occur. internal representation of
values.
OPENING FILES
Opening of files can be achieved in two ways:

 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.

Two or more modes can be combined using the bitwise operator |


TEXT FILE FUNCTIONS
 Reading/writing a single character from/to file :
get() – read a single character from text file and store in a buffer.
e.g file.get(ch);
put() - writing a single character in text file.
e.g. file.put(ch);

 Reading/writing a line from/to file:


getline() - read a line of text from text file stored in a buffer.
e.g file.getline(s,80,”\n”);
<<(insertion operator) – write a line to a file.
fin<<s;

 Reading/writing a word from/to file:


char ch[20];
fin.getline(ch,20, ‘ ‘);
We can use file>>ch for reading and file<<ch writing a word in text file. The
>> operator does not accept white spaces so it will stop when it encounters a
space after word and stores that word in ch.
A PROGRAM TO CREATE A TEXT FILE

#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.

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( ).
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 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 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.

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.
FUNCTIONS ASSOCIATED WITH FILE POINTERS

 get pointer: The functions associated with get pointer are


seekg()
tellg()

 put pointer: The functions associated with put pointer are


seekp()
tellp()

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 tellp() function is identical to the tellg() function, but it is


identified with the put pointer.
A PROGRAM TO USE FILE POINTERS IN A BINARY FILE

#include<fstream.h> void main() while(!fin.eof())


#include<process.h> { {
class student fstream fin(“xyz.dat”, ios::binary | fin.read((char*)&stu, sizeof stu);
{ ios::ate); if (stu.retroll() == roll)
private: if(!fin) {cout<<“enter data to be
int rollno; {cout<<“error in opening file”; modified”;
float total; exit(-1); stu.indata();
public: } fin.seekg(-sizeof(stu), ios::curr);
void indata() student stu; fin.write((char*)&stu, sizeof stu);
{ cin>>rollno>>total;} int roll; }
void outdata() cout<<“enter roll no of student whose
{cout<<rollno<<total;} record you want to modify”; fin.close();
} cin>>roll; }

The above program will read the binary file “xyz.dat” and modify
the record of the desired roll number.

You might also like