SlideShare a Scribd company logo
DataFileHandling
Prof. K. Adisesha
Learning Outcomes
 Introduction
 Stream in C++
 file stream operation
 Types of data Files
 Opening and Closing of Files
 File Modes
 Input and Output Operation file
 File pointers
2
Introduction
File Definition:
3
Introduction
File Definition:
 A file is a collection of related data stored in a particular
area on the disk.
 Programs can be designed to perform the read and write
operations on these files.
 In general a file is a sequence of bits, bytes, lines or
records whose meaning is defined by its user.
 C++ I/O occurs in streams, which are sequence of bytes.
 If bytes flows from device like a keyboard, a disk drive,
etc., to main memory, this is called input operation.
4
Stream in C++
Definition:
 A stream is sequence of bytes. In C++, a stream is a
general name given to flow of data.
 The three streams in C++ are as follows.
 Input Stream: The stream that supplies data to the
program is known as input stream.
 Output Stream: The stream that receives data from the
program is known as output stream.
 Error Stream: Error streams basically an output stream
used by the programs to the file or on the monitor to report
error messages.
5
File headers
fstream.h header file:
 The I / O system of C++ contains a set of classes that define
the file handling methods.
 These include:
 ifstream
 ofstream
 fstream
 These classes are derived from fstream base and from the
corresponding iostream.h.
 These classes, designed to manage the disk files, are declared
in fstream.h and therefore we must include this file in any
program that uses files.
6
file stream operation
Classes for file stream:
7
file stream operation
Classes for file stream operation:
8
Class Meanings
filebuf It sets the file buffer to read and write
fstreambase
It serves as a base class for the derived classes ifstream, ofstream
and fstream and contains open( ) and close( ) as member functions
ifstream
It supports input operations.
It contains open( ) with default input mode and inherits get( ),
getline( ), read( ), seekg( ) and tellg( ) functions from istream.
ofstream
It supports output operations.
It contains open( ) with default output mode and inherits put( ),
seekp( ), tellp( ) and write( ) functions from ostream
fstream
It supports simultaneous input and output operations.
It contains open( ) with default input mode and inherits all the
functions from istream and ostream classes through iostream
Types of Files
Types of data Files:
 Generally there are two types of files in C++:
 Text Files:
 A text file is a file that stores the information in ASCII
characters.
 Each line of text is terminated by a special character, known as
End of Line (EOL) or delimiter.
 Binary Files:
 A binary file is a file that contains information in the same
format as it is held in memory.
 In binary files, no delimiters are used for a line and no
translations occur here.
9
Files Operations
Opening Files:
 A file must first be opened before data can be read from it or
written to it.
 In C++ there are two ways to open a file with the file stream
object.
 Opening file using constructor.
 Opening file using open ( ) member function.
 The first method is preferred when a single file is used with a
stream.
 However for managing multiple files with the same stream, the
second method is preferred.
10
Opening Files
Opening file using constructor:
 In order to access a file, it has to be opened either in read, write
or append mode.
 In all the three file stream classes, a file can be opened by
passing a filename as the first parameter in the constructor
itself.
 The syntax for opening a file using constructor is:
 streamclass_name file_objectname (“filename”)
 Example:
 ofstream fout (“results.dat”);
 ifstream fin (“results.dat”);
11
Opening Files
Opening files using open( ):
 open( ) can be used to open multiple files that use the
same stream object.
 Syntax for opening a file using open ( ) member function:
file_stream_class stream_object;
stream_object.open (“file_name”);
 Example:
ofstream outfile;
outfile.open (“data”);
outfile.open (“text1.dat”);
12
Opening Files
Opening files using open( ):
 To open a file for both input and output, we declare
objects of fstream class.
 Syntax for fstream class using Constructor:
fstream fstream-object(“file name”, mode);
 syntax for open( ) member function:
fstream-object.open(“file name”, mode);
 Example:
fstream outfile;
outfile.open (“text1.dat”, mode);
13
File Modes
File Modes:
 While using constructors or open( ), the files were created
or opened in the default mode.
 There was only one argument passed, i.e. the filename.
 C++ provides a mechanism of opening a file in different
modes in which case the second parameter must be
explicitly passed.
 Syntax:
stream_object.open(“filename”, mode);
 Example:
fout.open(“data”, ios::app); //opens in append mode
14
File Modes
The lists of file modes are:
15
Mode method Stream Type Meaning
ios::app ofstream append to end of the file at opening time
ios::in ifstream open file for reading
ios::out ofstream open file for writing
ios::ate ifstream Open file for updating and move the file
pointer to the end of file
ios::trunc ofstream On opening, delete the contents of file
ios::nocreate ofstream Turn down opening if the file does not
exists
ios::binary ifstream Opening a binary file.
File Modes
Example of opening file:
16
Closing File
Closing File:
 The member function close( ) on its execution removes the
linkage between the file and the stream object.
 Syntax:
stream_object.close( );
 Example:
ofstream_obj.close( );
ifstream_obj.close( );
17
Operation in text file
Input and output operation in text file:
 The data in text files are organized into lines with new
line character as terminator.
 Text file need following types of character input and
output operations:
 put( ) function
 get( ) function
 getline( ) function
18
Text files
put( ) function in text file:
 The put( ) member function belongs to the class ofstream
and writes single character to the associated stream.
 Syntax:
ofstream_object.put(ch); // ch is the character variable.
 Example:
char ch=’A’;
ofstream fout(“text.txt”);
fout.put(ch);
 fout is the object of ofstream.
 Text is the name of the file.
 Value at ch is written to text.
19
Text files
get( ) function in text file:
 The get( ) member function belong to the class ifstream
and reads a single character from the associated stream.
 Syntax:
ifstream_object.get (ch); // ch is the character variable.
 Example:
char ch=’A’;
ifstream fin(“text.txt”);
fin.get (ch);;
 fin is the object of ifstream.
 Text is the name of the file.
 Value at ch is written to text.
20
Text files
getline( ) function in text file:
 The getline( ) member function belong to the class
ifstream, it reads a whole line from the associated stream.
 Syntax:
fin.getline(buffer, SIZE)
It reads SIZE characters from the file represented by the object fin or till the
new line character is encountered, whichever comes first into the buffer.
 Example:
char Student[SIZE];
ifstream fin;
fin.getline (Student, SIZE);
21
Binary files
Input and output operation in binary files:
 Binary files are very much use when we have to deal with
database consisting of records.
 The binary format is more accurate for storing the
numbers as they are stored in the exact internal
representation.
 There is no conversion while saving the data and hence it
is faster.
 Functions used to handle data in binary form are:
 write ( ) member function.
 read ( ) member function
22
Binary files
write ( ) member function in binary files:
 The write( ) member function belongs to the class ofstream and
which is used to write binary data to a file.
 These functions take 2 arguments.
 First is the address of the variable
 Second the size of the variable in bytes.
 Syntax:
ofstream_object.write((char *) & variable, sizeof(variable));
 The address of the variable must be type casted to pointer to character.
 Example: student s;
ofstream fout(“std.dat”, ios::binary);
fout.write((char *) &s, sizeof(s));
23
Binary files
Detecting End of file eof( ):
 Detecting end of file is necessary for preventing any further
attempt to read data from the file.
 eof( ) is a member function of ios class.
 It returns a non-zero (true) value if the end of file condition is
encountered while reading; otherwise returns a zero (false).
 Example:
ifstream fin;
if(fin.eof( ))
{ statements; }
 This is used to execute set statements on reaching the end of the file by
the object fin.
24
File pointers
File pointers and their manipulation:
 In C++, the file I/O operations are associated with the two
file pointers:
 Input pointer (get pointer)
 Output pointer (put pointer)
 We use these pointers to move through files while reading
or writing.
 Each time an input or output operation takes place,
appropriate pointer is automatically advanced.
25
File pointers
File pointers and their manipulation:
 There are three modes under which we can open a file:
 Read only mode:
 Write only mode
 Append mode
 When a file is opened in read only mode, the input pointer is
automatically set at the beginning of the file.
 When a file is opened in write only mode, the existing
contents are deleted and output pointer is set at the beginning
 If we want to open an existing file to add more data, the file is
opened in append mode. This moves the file pointer to the end
of the file.
26
File pointers
Functions for manipulation of file pointers:
 To move file pointers to any desired position inside a file,
file stream classes support the following functions:
 seekg() - Moves get file pointer to a specific location
 seekp() - Moves put file pointer to a specific location
 tellg() - Returns the current position of the get pointer
 tellp() - Returns the current position of the put pointer
 The seekp() and tellp() are member functions of ofstream
 The seekg() and tellg() are member functions of ifstream.
 All four functions are available in the class fstream. 27
File pointers
seekg( ) file pointers:
28
File pointers
seekg(offset, seekdir) file pointers:
 The seekg(offset, seekdir) has two arguments: offset and
seekdir.
 The offset indicates the number of bytes the get pointer is to be
moved from seekdir position.
 Syntax:
stream_objectname.seekg(offset, origin_value);
 Example:
29
seekg( ) function option Action performed
object.seekg(0, ios::beg) Take get pointer to the beginning of the file
object.seekg(0, ios::cur) Stay get pointer at the current position.
object.seekg(-m, ios::end) Go backward by m bytes from the file end.
File pointers
seekg(offset, seekdir) file pointers:
30
File pointers
seekp() file pointers:
 Move the put pointer to a specified location from the beginning
of a file.
 There are two types:
 seekp(long);
 seekp(offset, seekdir);
 The seekp(long) moves the put pointer to a specified location
from the beginning of a file.
 Example:
infile.seekp(20);
31
File pointers
tellg ( ) and tellp( )file pointers:
 tellg( ) returns the current position of the get pointer.
 Syntax:
position = ifstream_object.tellg( );
 Example:
int position= fin.tellg();
 tellp( ) returns the current position of the put pointer.
 Syntax:
position = ifstream_object.tellp( );
 Example:
int position = fin.tellp();
32
File pointers
tellp( )file pointers:
33
File pointers
Functions for Manipulation of file pointers:
34
Operation on binary file
Basic operation on binary file in C++:
 Searching
 Appending data
 Inserting data in sorted files
 Deleting a record
 Modifying data.
35

More Related Content

PDF
Class and object
PDF
file handling c++
PPSX
Files in c++
PPTX
Data structure and algorithm
PPTX
Stream classes in C++
PDF
Arrays in C++
PPTX
Data Structure and Algorithms
PDF
Files and streams
Class and object
file handling c++
Files in c++
Data structure and algorithm
Stream classes in C++
Arrays in C++
Data Structure and Algorithms
Files and streams

What's hot (20)

PPTX
Vi editor
PPT
Files in c++ ppt
PPT
PPTX
Vim Editor And Basic Scripting (Ch-7)
PPTX
PPT
File handling in C++
PPTX
Dbms 4NF & 5NF
PPTX
Unix
PPTX
System calls
PPTX
Function C programming
PDF
input/ output in java
PPT
Introduction to Compiler design
PPTX
The Relational Database Model
PPTX
PDF
Object oriented programming c++
PPTX
Procedural vs. object oriented programming
PPTX
FIle Organization.pptx
PPT
Stack a Data Structure
PPTX
Network software
PPT
Data Structure and Algorithms Linked List
Vi editor
Files in c++ ppt
Vim Editor And Basic Scripting (Ch-7)
File handling in C++
Dbms 4NF & 5NF
Unix
System calls
Function C programming
input/ output in java
Introduction to Compiler design
The Relational Database Model
Object oriented programming c++
Procedural vs. object oriented programming
FIle Organization.pptx
Stack a Data Structure
Network software
Data Structure and Algorithms Linked List
Ad

Similar to Data file handling (20)

PDF
Files in C++.pdf is the notes of cpp for reference
PPTX
Filesin c++
PPTX
File handling.pptx
PDF
Filesinc 130512002619-phpapp01
PPT
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
PPTX
File management in C++
PPTX
Working with files in c++. file handling
PPTX
File Handling
PPTX
Data file handling in c++
PPT
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
PPT
File handling in_c
PPT
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
PPT
file_handling_in_c.ppt......................................
PPTX
Data file operations in C++ Base
PPTX
Data file handling
PPTX
Introduction-to-Streams-and-Files-in-C.pptx
PDF
File Handling.pdffile handling ppt final
PPTX
basics of file handling
PPTX
Basics of file handling
Files in C++.pdf is the notes of cpp for reference
Filesin c++
File handling.pptx
Filesinc 130512002619-phpapp01
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
File management in C++
Working with files in c++. file handling
File Handling
Data file handling in c++
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
File handling in_c
file_handling_in_c.pptbbbbbbbbbbbbbbbbbbbbb
file_handling_in_c.ppt......................................
Data file operations in C++ Base
Data file handling
Introduction-to-Streams-and-Files-in-C.pptx
File Handling.pdffile handling ppt final
basics of file handling
Basics of file handling
Ad

More from Prof. Dr. K. Adisesha (20)

PDF
MACHINE LEARNING Notes by Dr. K. Adisesha
PDF
Probabilistic and Stochastic Models Unit-3-Adi.pdf
PDF
Genetic Algorithm in Machine Learning PPT by-Adi
PDF
Unsupervised Machine Learning PPT Adi.pdf
PDF
Supervised Machine Learning PPT by K. Adisesha
PDF
Introduction to Machine Learning PPT by K. Adisesha
PPSX
Design and Analysis of Algorithms ppt by K. Adi
PPSX
Data Structure using C by Dr. K Adisesha .ppsx
PDF
Operating System-4 "File Management" by Adi.pdf
PDF
Operating System-3 "Memory Management" by Adi.pdf
PDF
Operating System Concepts Part-1 by_Adi.pdf
PDF
Operating System-2_Process Managementby_Adi.pdf
PDF
Software Engineering notes by K. Adisesha.pdf
PDF
Software Engineering-Unit 1 by Adisesha.pdf
PDF
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
PDF
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
PDF
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
PDF
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
PDF
Computer Networks Notes by -Dr. K. Adisesha
PDF
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
MACHINE LEARNING Notes by Dr. K. Adisesha
Probabilistic and Stochastic Models Unit-3-Adi.pdf
Genetic Algorithm in Machine Learning PPT by-Adi
Unsupervised Machine Learning PPT Adi.pdf
Supervised Machine Learning PPT by K. Adisesha
Introduction to Machine Learning PPT by K. Adisesha
Design and Analysis of Algorithms ppt by K. Adi
Data Structure using C by Dr. K Adisesha .ppsx
Operating System-4 "File Management" by Adi.pdf
Operating System-3 "Memory Management" by Adi.pdf
Operating System Concepts Part-1 by_Adi.pdf
Operating System-2_Process Managementby_Adi.pdf
Software Engineering notes by K. Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Computer Networks Notes by -Dr. K. Adisesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha

Recently uploaded (20)

PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
master seminar digital applications in india
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Pharma ospi slides which help in ospi learning
Pharmacology of Heart Failure /Pharmacotherapy of CHF
O5-L3 Freight Transport Ops (International) V1.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
The Final Stretch: How to Release a Game and Not Die in the Process.
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Renaissance Architecture: A Journey from Faith to Humanism
Anesthesia in Laparoscopic Surgery in India
human mycosis Human fungal infections are called human mycosis..pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
master seminar digital applications in india
TR - Agricultural Crops Production NC III.pdf
Microbial disease of the cardiovascular and lymphatic systems
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Microbial diseases, their pathogenesis and prophylaxis
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Pharma ospi slides which help in ospi learning

Data file handling

  • 2. Learning Outcomes  Introduction  Stream in C++  file stream operation  Types of data Files  Opening and Closing of Files  File Modes  Input and Output Operation file  File pointers 2
  • 4. Introduction File Definition:  A file is a collection of related data stored in a particular area on the disk.  Programs can be designed to perform the read and write operations on these files.  In general a file is a sequence of bits, bytes, lines or records whose meaning is defined by its user.  C++ I/O occurs in streams, which are sequence of bytes.  If bytes flows from device like a keyboard, a disk drive, etc., to main memory, this is called input operation. 4
  • 5. Stream in C++ Definition:  A stream is sequence of bytes. In C++, a stream is a general name given to flow of data.  The three streams in C++ are as follows.  Input Stream: The stream that supplies data to the program is known as input stream.  Output Stream: The stream that receives data from the program is known as output stream.  Error Stream: Error streams basically an output stream used by the programs to the file or on the monitor to report error messages. 5
  • 6. File headers fstream.h header file:  The I / O system of C++ contains a set of classes that define the file handling methods.  These include:  ifstream  ofstream  fstream  These classes are derived from fstream base and from the corresponding iostream.h.  These classes, designed to manage the disk files, are declared in fstream.h and therefore we must include this file in any program that uses files. 6
  • 7. file stream operation Classes for file stream: 7
  • 8. file stream operation Classes for file stream operation: 8 Class Meanings filebuf It sets the file buffer to read and write fstreambase It serves as a base class for the derived classes ifstream, ofstream and fstream and contains open( ) and close( ) as member functions ifstream It supports input operations. It contains open( ) with default input mode and inherits get( ), getline( ), read( ), seekg( ) and tellg( ) functions from istream. ofstream It supports output operations. It contains open( ) with default output mode and inherits put( ), seekp( ), tellp( ) and write( ) functions from ostream fstream It supports simultaneous input and output operations. It contains open( ) with default input mode and inherits all the functions from istream and ostream classes through iostream
  • 9. Types of Files Types of data Files:  Generally there are two types of files in C++:  Text Files:  A text file is a file that stores the information in ASCII characters.  Each line of text is terminated by a special character, known as End of Line (EOL) or delimiter.  Binary Files:  A binary file is a file that contains information in the same format as it is held in memory.  In binary files, no delimiters are used for a line and no translations occur here. 9
  • 10. Files Operations Opening Files:  A file must first be opened before data can be read from it or written to it.  In C++ there are two ways to open a file with the file stream object.  Opening file using constructor.  Opening file using open ( ) member function.  The first method is preferred when a single file is used with a stream.  However for managing multiple files with the same stream, the second method is preferred. 10
  • 11. Opening Files Opening file using constructor:  In order to access a file, it has to be opened either in read, write or append mode.  In all the three file stream classes, a file can be opened by passing a filename as the first parameter in the constructor itself.  The syntax for opening a file using constructor is:  streamclass_name file_objectname (“filename”)  Example:  ofstream fout (“results.dat”);  ifstream fin (“results.dat”); 11
  • 12. Opening Files Opening files using open( ):  open( ) can be used to open multiple files that use the same stream object.  Syntax for opening a file using open ( ) member function: file_stream_class stream_object; stream_object.open (“file_name”);  Example: ofstream outfile; outfile.open (“data”); outfile.open (“text1.dat”); 12
  • 13. Opening Files Opening files using open( ):  To open a file for both input and output, we declare objects of fstream class.  Syntax for fstream class using Constructor: fstream fstream-object(“file name”, mode);  syntax for open( ) member function: fstream-object.open(“file name”, mode);  Example: fstream outfile; outfile.open (“text1.dat”, mode); 13
  • 14. File Modes File Modes:  While using constructors or open( ), the files were created or opened in the default mode.  There was only one argument passed, i.e. the filename.  C++ provides a mechanism of opening a file in different modes in which case the second parameter must be explicitly passed.  Syntax: stream_object.open(“filename”, mode);  Example: fout.open(“data”, ios::app); //opens in append mode 14
  • 15. File Modes The lists of file modes are: 15 Mode method Stream Type Meaning ios::app ofstream append to end of the file at opening time ios::in ifstream open file for reading ios::out ofstream open file for writing ios::ate ifstream Open file for updating and move the file pointer to the end of file ios::trunc ofstream On opening, delete the contents of file ios::nocreate ofstream Turn down opening if the file does not exists ios::binary ifstream Opening a binary file.
  • 16. File Modes Example of opening file: 16
  • 17. Closing File Closing File:  The member function close( ) on its execution removes the linkage between the file and the stream object.  Syntax: stream_object.close( );  Example: ofstream_obj.close( ); ifstream_obj.close( ); 17
  • 18. Operation in text file Input and output operation in text file:  The data in text files are organized into lines with new line character as terminator.  Text file need following types of character input and output operations:  put( ) function  get( ) function  getline( ) function 18
  • 19. Text files put( ) function in text file:  The put( ) member function belongs to the class ofstream and writes single character to the associated stream.  Syntax: ofstream_object.put(ch); // ch is the character variable.  Example: char ch=’A’; ofstream fout(“text.txt”); fout.put(ch);  fout is the object of ofstream.  Text is the name of the file.  Value at ch is written to text. 19
  • 20. Text files get( ) function in text file:  The get( ) member function belong to the class ifstream and reads a single character from the associated stream.  Syntax: ifstream_object.get (ch); // ch is the character variable.  Example: char ch=’A’; ifstream fin(“text.txt”); fin.get (ch);;  fin is the object of ifstream.  Text is the name of the file.  Value at ch is written to text. 20
  • 21. Text files getline( ) function in text file:  The getline( ) member function belong to the class ifstream, it reads a whole line from the associated stream.  Syntax: fin.getline(buffer, SIZE) It reads SIZE characters from the file represented by the object fin or till the new line character is encountered, whichever comes first into the buffer.  Example: char Student[SIZE]; ifstream fin; fin.getline (Student, SIZE); 21
  • 22. Binary files Input and output operation in binary files:  Binary files are very much use when we have to deal with database consisting of records.  The binary format is more accurate for storing the numbers as they are stored in the exact internal representation.  There is no conversion while saving the data and hence it is faster.  Functions used to handle data in binary form are:  write ( ) member function.  read ( ) member function 22
  • 23. Binary files write ( ) member function in binary files:  The write( ) member function belongs to the class ofstream and which is used to write binary data to a file.  These functions take 2 arguments.  First is the address of the variable  Second the size of the variable in bytes.  Syntax: ofstream_object.write((char *) & variable, sizeof(variable));  The address of the variable must be type casted to pointer to character.  Example: student s; ofstream fout(“std.dat”, ios::binary); fout.write((char *) &s, sizeof(s)); 23
  • 24. Binary files Detecting End of file eof( ):  Detecting end of file is necessary for preventing any further attempt to read data from the file.  eof( ) is a member function of ios class.  It returns a non-zero (true) value if the end of file condition is encountered while reading; otherwise returns a zero (false).  Example: ifstream fin; if(fin.eof( )) { statements; }  This is used to execute set statements on reaching the end of the file by the object fin. 24
  • 25. File pointers File pointers and their manipulation:  In C++, the file I/O operations are associated with the two file pointers:  Input pointer (get pointer)  Output pointer (put pointer)  We use these pointers to move through files while reading or writing.  Each time an input or output operation takes place, appropriate pointer is automatically advanced. 25
  • 26. File pointers File pointers and their manipulation:  There are three modes under which we can open a file:  Read only mode:  Write only mode  Append mode  When a file is opened in read only mode, the input pointer is automatically set at the beginning of the file.  When a file is opened in write only mode, the existing contents are deleted and output pointer is set at the beginning  If we want to open an existing file to add more data, the file is opened in append mode. This moves the file pointer to the end of the file. 26
  • 27. File pointers Functions for manipulation of file pointers:  To move file pointers to any desired position inside a file, file stream classes support the following functions:  seekg() - Moves get file pointer to a specific location  seekp() - Moves put file pointer to a specific location  tellg() - Returns the current position of the get pointer  tellp() - Returns the current position of the put pointer  The seekp() and tellp() are member functions of ofstream  The seekg() and tellg() are member functions of ifstream.  All four functions are available in the class fstream. 27
  • 28. File pointers seekg( ) file pointers: 28
  • 29. File pointers seekg(offset, seekdir) file pointers:  The seekg(offset, seekdir) has two arguments: offset and seekdir.  The offset indicates the number of bytes the get pointer is to be moved from seekdir position.  Syntax: stream_objectname.seekg(offset, origin_value);  Example: 29 seekg( ) function option Action performed object.seekg(0, ios::beg) Take get pointer to the beginning of the file object.seekg(0, ios::cur) Stay get pointer at the current position. object.seekg(-m, ios::end) Go backward by m bytes from the file end.
  • 31. File pointers seekp() file pointers:  Move the put pointer to a specified location from the beginning of a file.  There are two types:  seekp(long);  seekp(offset, seekdir);  The seekp(long) moves the put pointer to a specified location from the beginning of a file.  Example: infile.seekp(20); 31
  • 32. File pointers tellg ( ) and tellp( )file pointers:  tellg( ) returns the current position of the get pointer.  Syntax: position = ifstream_object.tellg( );  Example: int position= fin.tellg();  tellp( ) returns the current position of the put pointer.  Syntax: position = ifstream_object.tellp( );  Example: int position = fin.tellp(); 32
  • 34. File pointers Functions for Manipulation of file pointers: 34
  • 35. Operation on binary file Basic operation on binary file in C++:  Searching  Appending data  Inserting data in sorted files  Deleting a record  Modifying data. 35