SlideShare a Scribd company logo
1 of 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 Files and Arrays( graduating to files ):
DIFFERENCE BETWEEN ARRAYS AND 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
data between programs.
Files can be used to share data between
programs.
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
Output Stream
Disk
File
C++
Program
Read
data
Extract from
input stream
Insert into
output stream
Write
data
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
IOSTREAM
FSTREAM
ISTREAM
get ()
getline()
read()
>>
OSTREAM
put ()
write()
<<
IFSTREAM
seekg()
tellg()
open()
>>
OFSTREAM
seekp()
tellp()
open()
<<
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
lines
In text files various character translations are
performed such as “r+f”(carriage return-
linefeed combination)is converted into “n”(new
line) while reading from a file and vice-versa
while writing.
In binary files no such translations are
performed.
Portability Portable: one can easily transfer text file from
one computer to the other
Non portable: Binary files are
dependent. If the new computer uses
a different internal representation for
values they cannot be transferred.
Storage of
numbers
In text files when we store numbers they are
stored as characters eg if we store a decimal no
42.9876 in a text file it occupies 7 bytes
In a binary file 42.9876 is stored in 4
bytes
Text Files Binary Files
Readability Are readable and thus can be
easily edited using any word
editor.
Not readable
Storage Occupy more space due to
character conversions
Occupy less space.
Accuracy While reading/writing of
numbers, some conversion
errors may occur.
Highly accurate for numbers
because it stores the exact
internal representation of
values.
DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES contd…
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 filen”;
fout<<“this text file contains alphabets and numbersn”;
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.
#include<fstream.h>
void main()
{
ifstream fin(“abc.txt”);
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
}
A PROGRAM TO READ A TEXT FILE CHRACTER
BY CHARACTER
The above program will read a text file “abc.txt” one character at a
time and display it on the screen.
#include<fstream.h>
void main()
{
ifstream fin(“abc.txt”);
char ch[20];
while(!fin.eof())
{
fin>>ch;
cout<<ch;
}
fin.close();
}
A PROGRAM TO READ A TEXT FILE WORD BY
WORD
The above program will read a text file “abc.txt” one word at a time
and display it on the screen.
#include<fstream.h>
void main()
{
ifstream fin(“abc.txt”);
char ch[80];
while(!fin.eof())
{
fin.getline(ch,80,”n”);
cout<<ch;
}
fin.close();
}
A PROGRAM TO READ A TEXT FILE LINE BY
LINE
The above program will read a text file “abc.txt” one line at a time
and display it on the screen.
 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( ).
BINARY FILE FUNCTIONS
#include<fstream.h>
class student
{
private:
int rollno;
float total;
public:
void indata()
{ cin>>rollno>>total;}
void outdata()
{cout<<rollno<<total;}
}
A PROGRAM TO CREATE A BINARY FILE
The above program will create a binary file “xyz.dat” and store n
records in it.
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();
}
#include<fstream.h>
#include<process.h>
class student
{
private:
int rollno;
float total;
public:
void indata()
{ cin>>rollno>>total;}
void outdata()
{cout<<rollno<<total;}
}
A PROGRAM TO READ A BINARY FILE
The above program will read the binary file “xyz.dat” and display all
records stored in it.
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();
}
#include<fstream.h>
#include<process.h>
class student
{
private:
int rollno;
float total;
public:
void indata()
{ cin>>rollno>>total;}
void outdata()
{cout<<rollno<<total;}
}
A PROGRAM TO ADD NEW RECORDS TO BINARY FILE
The above program will add n new records at the end of the binary
file “xyz.dat”.
void main()
{
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;}
}
A PROGRAM TO DELETE A RECORD FROM BINARY FILE
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.
void main()
{
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”);
}
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
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.
FILE POINTERS contd…
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
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.
seekg()/seekp() FUNCTIONS contd…
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.
#include<fstream.h>
#include<process.h>
class student
{
private:
int rollno;
float total;
public:
void indata()
{ cin>>rollno>>total;}
void outdata()
{cout<<rollno<<total;}
}
A PROGRAM TO USE FILE POINTERS IN A BINARY FILE
The above program will read the binary file “xyz.dat” and modify
the record of the desired roll number.
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;
while(!fin.eof())
{
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();
}

More Related Content

What's hot (20)

file handling c++
file handling c++file handling c++
file handling c++
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Structure in c
Structure in cStructure in c
Structure in c
 
Pre processor directives in c
Pre processor directives in cPre processor directives in c
Pre processor directives in c
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
 
class and objects
class and objectsclass and objects
class and objects
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Strings
StringsStrings
Strings
 
13. Pointer and 2D array
13. Pointer  and  2D array13. Pointer  and  2D array
13. Pointer and 2D array
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
Structure in C
Structure in CStructure in C
Structure in C
 

Viewers also liked

basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Data file handling
Data file handlingData file handling
Data file handlingTAlha MAlik
 
Creating, Updating and Deleting Document in MongoDB
Creating, Updating and Deleting Document in MongoDBCreating, Updating and Deleting Document in MongoDB
Creating, Updating and Deleting Document in MongoDBWildan Maulana
 
File handling in_c
File handling in_cFile handling in_c
File handling in_csanya6900
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and outputOnline
 
Managing console input and output
Managing console input and outputManaging console input and output
Managing console input and outputgourav kottawar
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1Vineeta Garg
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsVineeta Garg
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3Shaili Choudhary
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functionsVineeta Garg
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraintsVineeta Garg
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patilwidespreadpromotion
 

Viewers also liked (20)

basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
File Pointers
File PointersFile Pointers
File Pointers
 
File handling
File handlingFile handling
File handling
 
Data file handling
Data file handlingData file handling
Data file handling
 
Creating, Updating and Deleting Document in MongoDB
Creating, Updating and Deleting Document in MongoDBCreating, Updating and Deleting Document in MongoDB
Creating, Updating and Deleting Document in MongoDB
 
Chap 1 c++
Chap 1 c++Chap 1 c++
Chap 1 c++
 
Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
 
Filehandling
FilehandlingFilehandling
Filehandling
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
 
Managing console input and output
Managing console input and outputManaging console input and output
Managing console input and output
 
Managing console
Managing consoleManaging console
Managing console
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraints
 
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil13. Indexing MTrees - Data Structures using C++ by Varsha Patil
13. Indexing MTrees - Data Structures using C++ by Varsha Patil
 
Pp
PpPp
Pp
 

Similar to Data file handling in c++

FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSVenugopalavarma Raja
 
File management in C++
File management in C++File management in C++
File management in C++apoorvaverma33
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))Papu Kumar
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++Teguh Nugraha
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugevsol7206
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing fileskeeeerty
 
Data file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing filesData file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing filesKeerty Smile
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5YOGESH SINGH
 
Deletion of a Record from a File - K Karun
Deletion of a Record from a File - K KarunDeletion of a Record from a File - K Karun
Deletion of a Record from a File - K KarunDipayan Sarkar
 

Similar to Data file handling in c++ (20)

data file handling
data file handlingdata file handling
data file handling
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
File Handling
File HandlingFile Handling
File Handling
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
File management in C++
File management in C++File management in C++
File management in C++
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
 
Data file handling
Data file handlingData file handling
Data file handling
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
 
Data file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing filesData file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing files
 
Unit 8
Unit 8Unit 8
Unit 8
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
Deletion of a Record from a File - K Karun
Deletion of a Record from a File - K KarunDeletion of a Record from a File - K Karun
Deletion of a Record from a File - K Karun
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 

More from Vineeta Garg

More from Vineeta Garg (6)

Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
 
GUI programming
GUI programmingGUI programming
GUI programming
 
SQL
SQLSQL
SQL
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 

Recently uploaded

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 

Recently uploaded (20)

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 

Data file handling in c++

  • 2. What if a FILE? A file is a stream of bytes stored on some secondary storage devices.
  • 3. 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.
  • 4. Difference between Files and Arrays( graduating to files ): DIFFERENCE BETWEEN ARRAYS AND 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 data between programs. Files can be used to share data between programs.
  • 5. 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 Output Stream Disk File C++ Program Read data Extract from input stream Insert into output stream Write data
  • 6. 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 IOSTREAM FSTREAM ISTREAM get () getline() read() >> OSTREAM put () write() << IFSTREAM seekg() tellg() open() >> OFSTREAM seekp() tellp() open() <<
  • 7. 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.
  • 8. 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.
  • 9. DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES These differ on six main parameters: TEXT FILES BINARY FILES Handling of new lines In text files various character translations are performed such as “r+f”(carriage return- linefeed combination)is converted into “n”(new line) while reading from a file and vice-versa while writing. In binary files no such translations are performed. Portability Portable: one can easily transfer text file from one computer to the other Non portable: Binary files are dependent. If the new computer uses a different internal representation for values they cannot be transferred. Storage of numbers In text files when we store numbers they are stored as characters eg if we store a decimal no 42.9876 in a text file it occupies 7 bytes In a binary file 42.9876 is stored in 4 bytes
  • 10. Text Files Binary Files Readability Are readable and thus can be easily edited using any word editor. Not readable Storage Occupy more space due to character conversions Occupy less space. Accuracy While reading/writing of numbers, some conversion errors may occur. Highly accurate for numbers because it stores the exact internal representation of values. DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES contd…
  • 11. 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
  • 12. 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.
  • 13. 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 |
  • 14. 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.
  • 15. A PROGRAM TO CREATE A TEXT FILE #include<fstream.h> void main() { ofstream fout(“abc.txt”); fout<<“ i am creating a new text filen”; fout<<“this text file contains alphabets and numbersn”; 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.
  • 16. #include<fstream.h> void main() { ifstream fin(“abc.txt”); char ch; while(!fin.eof()) { fin.get(ch); cout<<ch; } fin.close(); } A PROGRAM TO READ A TEXT FILE CHRACTER BY CHARACTER The above program will read a text file “abc.txt” one character at a time and display it on the screen.
  • 17. #include<fstream.h> void main() { ifstream fin(“abc.txt”); char ch[20]; while(!fin.eof()) { fin>>ch; cout<<ch; } fin.close(); } A PROGRAM TO READ A TEXT FILE WORD BY WORD The above program will read a text file “abc.txt” one word at a time and display it on the screen.
  • 18. #include<fstream.h> void main() { ifstream fin(“abc.txt”); char ch[80]; while(!fin.eof()) { fin.getline(ch,80,”n”); cout<<ch; } fin.close(); } A PROGRAM TO READ A TEXT FILE LINE BY LINE The above program will read a text file “abc.txt” one line at a time and display it on the screen.
  • 19.  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( ). BINARY FILE FUNCTIONS
  • 20. #include<fstream.h> class student { private: int rollno; float total; public: void indata() { cin>>rollno>>total;} void outdata() {cout<<rollno<<total;} } A PROGRAM TO CREATE A BINARY FILE The above program will create a binary file “xyz.dat” and store n records in it. 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(); }
  • 21. #include<fstream.h> #include<process.h> class student { private: int rollno; float total; public: void indata() { cin>>rollno>>total;} void outdata() {cout<<rollno<<total;} } A PROGRAM TO READ A BINARY FILE The above program will read the binary file “xyz.dat” and display all records stored in it. 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(); }
  • 22. #include<fstream.h> #include<process.h> class student { private: int rollno; float total; public: void indata() { cin>>rollno>>total;} void outdata() {cout<<rollno<<total;} } A PROGRAM TO ADD NEW RECORDS TO BINARY FILE The above program will add n new records at the end of the binary file “xyz.dat”. void main() { 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(); }
  • 23. #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;} } A PROGRAM TO DELETE A RECORD FROM BINARY FILE 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. void main() { 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”); }
  • 24. 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
  • 25. 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. FILE POINTERS contd…
  • 26. 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.
  • 27. 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
  • 28. 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. seekg()/seekp() FUNCTIONS contd…
  • 29. 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.
  • 30. #include<fstream.h> #include<process.h> class student { private: int rollno; float total; public: void indata() { cin>>rollno>>total;} void outdata() {cout<<rollno<<total;} } A PROGRAM TO USE FILE POINTERS IN A BINARY FILE The above program will read the binary file “xyz.dat” and modify the record of the desired roll number. 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; while(!fin.eof()) { 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(); }