SlideShare a Scribd company logo
Course Code CSE2001
Object Oriented Programming with C++
Type LTP
Credits 4
UNIT 5_ PART 2 : IOstreams and Fi les
OOPs using C++
Object Oriented Programming with C++
Course Code: CSE2001
UNIT 5 : CSE2001 IOstreams and Fi les
UNIT 5 : IOstreams and Files
 5.1 IOstreams
5.2 Manipulators
5.3 overloading Inserters(<<) and
Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects into/from
files
5.6 binary files
C++ Files and Streams
A stream in simple words is flow of data.
C++ views each files as a stream.
The operations associated with files are
read and write
C++ provides various classes to support
these operations.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Streams
• Stream: an object that either delivers data to its
destination (screen, file, etc.) or that takes data from a
source (keyboard, file, etc.)
– it acts as a buffer between the data source and
destination
• Input stream: a stream that provides input to a program
– System.in is an input stream
• Output stream: a stream that accepts output from a
program
– System.out is an output stream
• A stream connects a program to an I/O object
– System.out connects a program to the screen
– System.in connects a program to the keyboard
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Binary Versus Text Files
• All data and programs are ultimately just zeros and ones
– each digit can have one of two values, hence binary
– bit is one binary digit
– byte is a group of eight bits
• Text files: the bits represent printable characters
– one byte per character for ASCII, the most common code
– for example,CPP source files are text files
– so is any file created with a "text editor"
• Binary files: the bits represent other types of encoded
information, such as executable instructions or numeric data
– these files are easily read by the computer but not humans
– they are not "printable" files
• actually, you can print them, but they will be
unintelligible
• "printable" means "easily readable by humans when
printed"
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
To perform file processing in C++, the
header files essential are <iostream> and
<fstream>
<fstream> includes <ifstream> and
<ofstream>
ios is the base class for all these classes.
These classes provide several member
functions that perform input/output
operations.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Abbreviated C++ class hierarchy for input output
streams
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
iostream -- contains basic information
required for all stream I/O operations
fstream -- contains information for
performing file I/O operations
iomanip -- contains information useful for
performing formatted I/O with parameterized
stream manipulators
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
How to open a file in C++ ?
ofstream outFile(“sample.dat”,
ios:out)
OR
ofstream outFile;
outFile.open(“sample.dat”, ios:out)
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
How to close a file in C++?
The file is closed implicitly when a destructor
for the corresponding object is called
OR
by using member function close:
outFile.close();
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
File Open Modes
ios:: app - (append) write all output to the end
of file
ios:: ate - data can be written anywhere in the
file
ios:: binary - read/write data in binary format
ios:: in - (input) open a file for input
ios::out - (output) open afile for output
ios: trunc -(truncate) discard the files’ contents
if it exists
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
File Open Modes
ios::nocreate - if the file does NOT exists, the
open operation fails
ios::noreplace - if the file exists, the open
operation fails
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Reading and printing a sequential file
inFile >> var1 >> var2 >> var3
outFile<<“Name: “<<var1<<“Age :
“<<var2<<endl;
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
167
File position pointer
<istream> and <ostream> classes provide
member functions for repositioning the
file pointer (the byte number of the next
byte in the file to be read or to be written.)
These member functions are:
seekg (seek get) for istream class
seekp (seek put) for ostream class
Examples of moving a file pointer
inFile.seekg(0) - repositions the file get pointer to
the beginning of the file
inFile.seekg(n, ios:beg) - repositions the file get
pointer to the n-th byte of the file
inFile.seekg(m, ios:end) -repositions the file get
pointer to the m-th byte from the end of
file
inFile.seekg(0, ios:end) - repositions the file get
pointer to the end of the file
The same operations can be performed with
<ostream> function member seekp.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Member functions tellg() and tellp()
Member functions tellg and tellp are provided
to return the current locations of the get and put
pointers, respectively.
long location = inFile.tellg();
To move the pointer relative to the current
location use ios::cur
inFile.seekg(n, ios::cur) - moves the file get
pointer n bytes forward.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5 : IOstreams and Files
5.1 IOstreams
 5.2 Manipulators
5.3 overloading Inserters(<<) and
Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects into/from
files
5.6 binary files
CSE2001 Object Oriented Programming with C++
UNIT 5 : IOstreams and Files
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
• Manipulators are helping functions that can modify the
input/output stream.
• It does not mean that we change the value of a variable, it
only modifies the I/O stream using insertion (<<) and
extraction (>>) operators.
• Manipulators are special functions that can be included in the
I/O statement to alter the format parameters of a stream.
• Manipulators are operators that are used to format the data
display.
• To access manipulators, the file iomanip.h should be included
in the program.
• For example, if we want to print the hexadecimal value of 100
then we can print it as:
• cout<<setbase(16)<<100
Types of Manipulators There are various types of manipulators:
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Manipulators without arguments: The most important
manipulators defined by the IOStream library are provided
below.
endl: It is defined in ostream. It is used to enter a new line
and after entering a new line it flushes (i.e. it forces all the
output written on the screen or in the file) the output
stream.
ws: It is defined in istream and is used to ignore the
whitespaces in the string sequence.
ends: It is also defined in ostream and it inserts a null
character into the output stream. It typically works with
std::ostrstream, when the associated output buffer needs
to be null-terminated to be processed as a C string.
flush: It is also defined in ostream and it flushes the output
stream, i.e. it forces all the output written on the screen or
in the file. Without flush, the output would be the same, but
may not appear in real-time.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
C++ Stream I/O -- Stream Manipulators
C++ provides various stream manipulators
that perform formatting tasks.
Stream manipulators are defined in
<iomanip>
These manipulators provide capabilities for
setting field widths,
setting precision,
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
C++ Stream I/O -- Stream
Manipulators
setting and unsetting format flags,
flushing streams,
inserting a "newline" and flushing
output stream,
skipping whitespace in input stream
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
I/O -- Stream Manipulators
setprecision ( )
 Select output precision, i.e., number of
significant digits to be printed.
 Example:
cout << setprecision (2) ; // two
significant digits
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
I/O -- Stream Manipulators
setw ( )
 Specify the field width (Can be used on
input or output, but only applies to next
insertion or extraction).
 Example:
cout << setw (4) ; // field is four
positions wide
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5 : IOstreams and Files
5.1 IOstreams
5.2 Manipulators
 5.3 overloading Inserters(<<)
and
Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects into/from
files
5.6 binary files
CSE2001 Object Oriented Programming with C++
UNIT 5 : IOstreams and Files
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
5.3 overloading Inserters(<<) and
Extractors(>>)
overloading Inserters(<<)
• Programmers frequently overload the inserter
(or insertion) and extractor (or extraction)
operators because they are the main output
and input functions for C++ programs. Each
function follows a fixed pattern.
Example:
Int variable;
Cin>>variable;
Cout<< variable;
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
example
friend ostream& operator<<(ostream& out, fraction
& f)
{
// format and print member variables of f
return out;
}
friend istream& operator>>(istream& in, fraction & f)
{
// read member variables of f
return in;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
• The patterns illustrated here assume that the
operator definitions are placed inside the class
(i.e., not just prototyped in the class).
• We must keep prototypes in the class, but we
can move the function bodies out of the class
by dropping the friend keyword.
• parts that cannot change: Both functions are
always implemented as friends
•operator<< always returns an ostream
reference has an ostream reference for the
first parameter operator>> always
• returns an istream reference has an istream
reference for the first parameter
• more flexible parts but still required by the
pattern:
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
• The second parameter for both operators is always
a class reference. The class name is always the
class for which the operator is overloaded
• programmer specified names:
• names for the ostream and istream reference
variables
• names for the output and input object reference
variables
• function specific operations:
• format and print member variables read values
from the input stream into the member variables
Both operators always end with a return
statement, and the returned value is always the
name of the first parameter
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5 : IOstreams and Files
5.1 IOstreams
5.2 Manipulators
5.3 overloading Inserters(<<) and
Extractors(>>)
 5.4 Sequential and Random files
5.5 writing and reading objects into/from
files
5.6 binary files
CSE2001 Object Oriented Programming with C++
UNIT 5 : IOstreams and Files
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
C++ Files and Streams
• C++ views each files as a sequence of bytes.
• Each file ends with an end-of-file marker.
• When a file is opened, an object is created and a
stream is associated with the object.
• To perform file processing in C++, the header
files <iostream.h> and <fstream.h> must be
included.
• <fstream.> includes <ifstream> and <ofstream>
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
193
5.4 Sequential and Random files
Updating a sequential file
• Data that is formatted and written to a
sequential file cannot be modified
easily without the risk of destroying
other data in the file.
• If we want to modify a record of data,
the new data may be longer than the old
one and it could overwrite parts of the
record following it.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Problems with sequential files
Sequential files are inappropriate for so-called
“instant access” applications in which a
particular record of information must be
located immediately.
These applications include banking systems,
point-of-sale systems, airline reservation
systems, (or any data-base system.)
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Random access files
• Instant access is possible with random
access files.
• Individual records of a random access
file can be accessed directly (and
quickly) without searching many other
records.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Sequential and Random files
• In a sequential access file, data is accessed in a linear,
sequential manner, from start to end. Each read or
write operation must follow the previous one.
• In contrast, in a random access file, data can be
accessed at any point in the file, without having to
read through the entire file first
• sequential access files
Simple and straightforward to implement, with
minimal hardware and software requirements. It is
inexpensive because it does not necessitate complex
indexing or search algorithms.
• Because data is stored in a linear fashion and can be
accessed predictably, it is extremely efficient for
dealing with large data sets.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Parameter Sequential Access Random Access
Access Speed
Sequential access files are slower compared
to random access files since accessing a
specific record requires reading through all
the previous records in the file
Random access files, on the other hand, allow
direct access to specific records, resulting in
faster access times.
Access Method
Sequential access files allow access to
records in a sequential manner
Random access files allow direct access to
specific records using an index, record
number, or key.
Record Ordering
Sequential access files store records in a
specific order, usually the order in which
they were added to the file.
Random access files do not have any specific
order of storing records.
Insertion of New
Record
Inserting a new record in a sequential access
file is relatively easy since new records are
added to the end of the file.
Random access files may require relocating
other records to maintain the order so
insertion becomes hard as compared to
sequential access.
Memory
Requirements
Sequential access files require less memory
than random access files since they do not
need to store any indexing information.
Random access files require more memory
because of indexing information
Search Flexibility
Search flexibility is limited in sequential
access file.
Random access files offer higher search
flexibility than sequential access files since
they allow for direct access to specific records
based on various search criteria
Record Sizes
In sequential access files, record sizes are
usually uniform
Random access files, record sizes can be
variable
File Organization
Sequential access files are typically organized
in a linear fashion
Random access files are typically indexed.
Examples Text files, Logs Database, Spreadsheet
198
Creating a sequential file
// Create a sequential file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
// ofstream constructor opens file
ofstream oC( "clients.dat", ios::out );
if ( !oC ) { // overloaded ! operator
cerr << "File could not be opened" << endl;
exit( 1 ); // prototype in stdlib.h
}
cout << "Enter the account, name, and
balance.n"
<< "Enter end-of-file to end input.n? ";
int account;
char name[ 30 ];
float balance;
while ( cin >> account >> name >> balance )
{
oC<< account << ' ' << name
<< ' ' << balance << 'n';
cout << "? ";
}
return 0; // ofstream destructor closes file
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
199
Creating a sequential file
// Create a sequential file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
// ofstream constructor opens file
ofstream outClientFile( "clients.dat", ios::out );
if ( !outClientFile ) { // overloaded ! operator
cerr << "File could not be opened" << endl;
exit( 1 ); // prototype in stdlib.h
}
cout << "Enter the account, name, and
balance.n"
<< "Enter end-of-file to end input.n? ";
int account;
char name[ 30 ];
float balance;
while ( cin >> account >> name >> balance )
{
outClientFile << account << ' ' << name
<< ' ' << balance << 'n';
cout << "? ";
}
return 0; // ofstream destructor closes file
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
200
Creating a sequential file
// Create a sequential file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
// ofstream constructor opens file
ofstream outClientFile( "clients.dat", ios::out );
if ( !outClientFile ) { // overloaded ! operator
cerr << "File could not be opened" << endl;
exit( 1 ); // prototype in stdlib.h
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Sequential file
cout << "Enter the account, name, and balance.n"
<< "Enter end-of-file to end input.n? ";
int account;
char name[ 30 ];
float balance;
while ( cin >> account >> name >> balance ) {
outClientFile << account << ' ' << name
<< ' ' << balance << 'n';
cout << "? ";
}
return 0; // ofstream destructor closes file
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
How to open a file in C++ ?
Ofstream outClientFile(“clients.dat”, ios:out)
OR
Ofstream outClientFile;
outClientFile.open(“clients.dat”, ios:out)
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
File Open Modes
ios:: app - (append) write all output to the end of file
ios:: ate - data can be written anywhere in the file
ios:: binary - read/write data in binary format
ios:: in - (input) open a file for input
ios::out - (output) open afile for output
ios: trunc -(truncate) discard the files’ contents if
it exists
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
204
File Open Modes cont.
ios:nocreate - if the file does NOT exists, the open
operation fails
ios:noreplace - if the file exists, the open operation
fails
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
205
How to close a file in C++?
The file is closed implicitly when a
destructor for the corresponding object is
called
OR
by using member function close:
outClientFile.close();
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
206
Reading and printing a sequential file
// Reading and printing a sequential file
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
#include <stdlib.h>
void outputLine( int, const char *, double );
int main()
{
// ifstream constructor opens the file
ifstream inClientFile( "clients.dat", ios::in );
if ( !inClientFile ) {
cerr << "File could not be openedn";
exit( 1 );
}
int account;
char name[ 30 ];
double balance;
cout << setiosflags( ios::left ) << setw( 10 ) << "Account"
<< setw( 13 ) << "Name" << "Balancen";
while ( inClientFile >> account >> name >> balance )
outputLine( account, name, balance );
return 0; // ifstream destructor closes the file
}
void outputLine( int acct, const char *name, double bal )
{
cout << setiosflags( ios::left ) << setw( 10 ) << acct
<< setw( 13 ) << name << setw( 7 ) << setprecision( 2 )
<< resetiosflags( ios::left )
<< setiosflags( ios::fixed | ios::showpoint )
<< bal << 'n';
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
208
File position pointer
<istream> and <ostream> classes provide member
functions for repositioning the file pointer (the byte
number of the next byte in the file to be read or to be
written.)
These member functions are:
seekg (seek get) for istream class
seekp (seek put) for ostream class
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
209
Examples of moving a file pointer
inClientFile.seekg(0) - repositions the file get pointer
to the beginning of the file
inClientFile.seekg(n, ios:beg) - repositions the file get
pointer to the n-th byte of the file
inClientFile.seekg(m, ios:end) -repositions the file get
pointer to the m-th byte from the end of file
nClientFile.seekg(0, ios:end) - repositions the file get
pointer to the end of the file
The same operations can be performed with
<ostream> function member seekp.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
210
Member functions tellg() and tellp().
Member functions tellg and tellp are provided to return
the current locations of the get and put pointers,
respectively.
long location = inClientFile.tellg();
To move the pointer relative to the current location use
ios:cur
inClientFile.seekg(n, ios:cur) - moves the file get pointer n
bytes forward.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
211
Updating a sequential file
Data that is formatted and written to a
sequential file cannot be modified easily
without the risk of destroying other data in
the file.
If we want to modify a record of data, the
new data may be longer than the old one and
it could overwrite parts of the record
following it.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Problems with sequential files
• Sequential files are inappropriate for so-called
“instant access” applications in which a particular
record of information must be located
immediately.
• These applications include banking systems, point-
of-sale systems, airline reservation systems, (or any
data-base system.)
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
213
Random access files
• Instant access is possible with random access files.
• Individual records of a random access file can be
accessed directly (and quickly) without searching
many other records.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
214
Example of a Program that Creates a Random
Access File
// Fig. 14.11: clntdata.h
// Definition of struct clientData used in
#ifndef CLNTDATA_H
#define CLNTDATA_H
struct clientData {
int accountNumber;
char lastName[ 15 ];
char firstName[ 10 ];
float balance;
};
#endif
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Creating a random access file
// Creating a randomly accessed file sequentially
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit1.dat", ios::out);
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
216
clientData blankClient = { 0, "", "", 0.0 };
for ( int i = 0; i < 100; i++ )
outCredit.write
(reinterpret_cast<const char *>( &blankClient ),
sizeof( clientData ) );
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
217
<ostream> memebr function write
The <ostream> member function write
outputs a fixed number of bytes beginning at
a specific location in memory to the specific
stream.
When the stream is associated with a file,
the data is written beginning at the location
in the file specified by the “put” file pointer.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
218
Writing data randomly to a random
file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit.dat", ios::ate );
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
219
cout << "Enter account number "
<< "(1 to 100, 0 to end input)n? ";
clientData client;
cin >> client.accountNumber;
while ( client.accountNumber > 0 &&
client.accountNumber <= 100 ) {
cout << "Enter lastname, firstname, balancen? ";
cin >> client.lastName >> client.firstName
>> client.balance;
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
220
outCredit.seekp( ( client.accountNumber - 1 ) *
sizeof( clientData ) );
outCredit.write(
reinterpret_cast<const char *>( &client ),
sizeof( clientData ) );
cout << "Enter account numbern? ";
cin >> client.accountNumber;
}
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
221
Reading data from a random file
#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
void outputLine( ostream&, const clientData & );
int main()
{
ifstream inCredit( "credit.dat", ios::in );
if ( !inCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
222
cout << setiosflags( ios::left ) << setw( 10 ) <<
"Account"
<< setw( 16 ) << "Last Name" << setw( 11 )
<< "First Name" << resetiosflags( ios::left )
<< setw( 10 ) << "Balance" << endl;
clientData client;
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
223
while ( inCredit && !inCredit.eof() ) {
if ( client.accountNumber != 0 )
outputLine( cout, client );
inCredit.read( reinterpret_cast<char *>( &client
),
sizeof( clientData ) );
}
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
224
void outputLine( ostream &output, const clientData &c
)
{
output << setiosflags( ios::left ) << setw( 10 )
<< c.accountNumber << setw( 16 ) << c.lastName
<< setw( 11 ) << c.firstName << setw( 10 )
<< setprecision( 2 ) << resetiosflags( ios::left )
<< setiosflags( ios::fixed | ios::showpoint )
<< c.balance << 'n';
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
The <istream> function read
inCredit.read (reinterpret_cast<char *>(&client),
sizeof(clientData));
The <istream> function inputs a specified (by
sizeof(clientData)) number of bytes from the
current position of the specified stream into an
object.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
226
Example of a Program that Creates
a Random Access File
/// Definition of struct clientData used in
#ifndef CLNTDATA_H
#define CLNTDATA_H
struct clientData {
int accountNumber;
char lastName[ 15 ];
char firstName[ 10 ];
float balance;
};
#endif
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
227
Creating a random access file
// Creating a randomly accessed file sequentially
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit1.dat", ios::out);
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
228
clientData blankClient = { 0, "", "", 0.0 };
for ( int i = 0; i < 100; i++ )
outCredit.write
(reinterpret_cast<const char *>(
&blankClient ),
sizeof( clientData ) );
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
229
<ostream> member function write
The <ostream> member function write
outputs a fixed number of bytes
beginning at a specific location in
memory to the specific stream.
When the stream is associated with a
file, the data is written beginning at the
location in the file specified by the “put”
file pointer.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
230
The write function expects a first
argument of type const char *, hence we
used the reinterpret_cast <const char
*> to convert the address of the
blankClient to a const char*.
The second argument of write is an
integer of type size_t specifying the
number of bytes to written. Thus the
sizeof( clientData ).
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
231
Writing data randomly to a random
file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit.dat", ios::ate );
if ( !outCredit ) {
cerr << "File could not be opened." <<
endl;
exit( 1 );
} UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
cout << "Enter account number "
<< "(1 to 100, 0 to end input)n? ";
clientData client;
cin >> client.accountNumber;
while ( client.accountNumber > 0 &&
client.accountNumber <= 100 ) {
cout << "Enter lastname, firstname, balancen? ";
cin >> client.lastName >> client.firstName
>> client.balance;
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
outCredit.seekp( ( client.accountNumber - 1 ) *
sizeof( clientData ) );
outCredit.write(
reinterpret_cast<const char *>( &client ),
sizeof( clientData ) );
cout << "Enter account numbern? ";
cin >> client.accountNumber;
}
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
234
Reading data from a random file
#include <iostream>
#include <iomanip.h>
#include <fstream>
#include <stdlib.h>
#include "clntdata.h"
void outputLine( ostream&, const clientData & );
int main()
{
ifstream inCredit( "credit.dat", ios::in );
if ( !inCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
cout << setiosflags( ios::left ) << setw( 10 ) <<
"Account"
<< setw( 16 ) << "Last Name" << setw( 11 )
<< "First Name" << resetiosflags( ios::left )
<< setw( 10 ) << "Balance" << endl;
clientData client;
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
while ( inCredit && !inCredit.eof() ) {
if ( client.accountNumber != 0 )
outputLine( cout, client );
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );
}
return 0;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
void outputLine( ostream &output, const
clientData &c )
{
output << setiosflags( ios::left ) << setw( 10 )
<< c.accountNumber << setw( 16 ) <<
c.lastName
<< setw( 11 ) << c.firstName << setw( 10 )
<< setprecision( 2 ) << resetiosflags(
ios::left )
<< setiosflags( ios::fixed | ios::showpoint )
<< c.balance << 'n';
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
238
The <istream> function read
inCredit.read (reinterpret_cast<char
*>(&client), sizeof(clientData));
The <istream> function inputs a specified
(by sizeof(clientData)) number of bytes
from the current position of the specified
stream into an object.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Stream I/O Format State Flags
ios::showpointwhen set, show trailing decimal
point and zeros
ios::showpos when set, show the + sign
before positive numbers
ios::basefield
ios::dec use base ten
ios::oct use base eight
ios::hex use base sixteen
239
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Stream I/O Format State Flags
ios::floatfield
ios::fixed use fixed number of digits
ios::scientific use "scientific" notation
ios::adjustfield
ios::left use left justification
ios::right use right justification
ios::internal left justify the sign, but right
justify the value
240
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
.setf ( )
 Allows the setting of an I/O stream
format flag.
 Examples:
// To show the + sign in front of
positive numbers
cout.setf (ios::showpos) ;
// To output the number in hexadecimal
cout.setf (ios::hex, ios::basefield) ;
241
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5 : IOstreams and Files
5.1 IOstreams
5.2 Manipulators
5.3 overloading Inserters(<<) and
Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects
into/from files
5.6 BINARY FILES
CSE2001 Object Oriented Programming with C++
UNIT 5 : IOstreams and Files
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Need for FILES in C++
• Data is very important. Every organization depends
on its data for continuing its business operations.
• If the data is lost, the organization has to be closed.
• This is the reason computers are primarily created
for handling data, especially for storing and
retrieving data.
• In later days, programs are developed to process the
data that is stored in the computer.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
C++ FILES APPLICATION
• To store data in a computer, we need files.
• For example, we can store employee data like employee
number, name and salary in a file in the computer and
later use it whenever we want.
• Similarly, we can store student data like student roll
number, name and marks in the computer. In
computers’ view, a file is nothing but collection of data
that is available to a program.
• Once we store data in a computer file, we can retrieve it
and use it depending on our requirements.
•
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
ADVANTAGES OF STORING A DATA IN A
FILE
• When the data is stored in a file, it is stored
permanently.
• This means that even though the computer is switched
off, the data is not removed from the memory since the
file is stored on hard disk or CD.
• This file data can be utilized later, whenever required.
• It is possible to update the file data.
• For example, we can add new data to the existing file,
delete unnecessary data from the file and modify the
available data of the file. This makes the file more
useful.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
ADVANTAGES OF STORING A DATA IN A
FILE
• Once the data is stored in a file, the same data can
be shared by various programs.
• For example, once employee data is stored in a file,
it can be used in a program to calculate employees’
net salaries or in another program to calculate
income tax payable by the employees.
• Files are highly useful to store huge amount of data.
For example, voters’ list or census data.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
TYPES OF FILES
• In Python, there are two types of files.
• They are:
 Text files
 Binary files
• Text files store the data in the form of characters. For
example, if we store employee name “Ganesh”, it will
be stored as 6 characters and the employee salary
8900.75 is stored as 7 characters.
• Text files are used to store characters or strings.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
TYPES OF FILES
• Binary files store entire data in the form of bytes,
i.e. a group of 8 bits each.
• For example, a character is stored as a byte and an
integer is stored in the form of 8 bytes (on a 64 bit
machine). When the data is retrieved from the
binary file, the programmer can retrieve the data
as bytes.
• Binary files can be used to store text, images,
audio and video. Image files are generally available
in .jpg, .gif or .png formats.
• We cannot use text files to store images as the
images do not contain characters.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
TYPES OF FILES
• On the other hand, images contain pixels which are
minute dots with which the picture is composed of.
• Each pixel can be represented by a bit, i.e. either 1
or 0. Since these bits can be handled by binary files,
we can say that they are highly suitable to store
images. It is very important to know how to create
files, store data in the files and retrieve the data
from the files.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
MODES OF FILES
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Binary file
• Binary file is a file with data stored in raw
format, the way it is stored in memory.
• For example, numbers are stored in binary
in memory.
• They are not converted to text (ASCII
characters) when writing to binary file.
• The data in binary format is not human
readable and cannot be read or modified
using text editors.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
• A binary file is a file whose content is
in a binary format consisting of a series
of sequential bytes, each of which is
eight bits in length.
• The content must be interpreted by a
program or a hardware processor that
understands in advance exactly how
that content is formatted and how to
read the data.
Binary file
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
• For example, only Microsoft Word and certain other
word processing programs can interpret
the formatting information in a Word
document.
• Executable files, compiled programs,
SAS and SPSS system files,
spreadsheets, compressed files, and
graphic (image) files are all examples
of binary files.
Binary file
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Binary file
• To write a binary file in C++ use write method. It is
used to write a given number of bytes on the given
stream, starting at the position of the "put" pointer.
• The file is extended if the put pointer is current at
the end of the file. If this pointer points into the
middle of the file, characters in the file are
overwritten with the new data.
• If any error has occurred during writing in the file,
the stream is placed in an error state.
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Binary file
• Syntax of write method
• ostream& write(const char*,
int);
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Binary file Example Code
#include<iostream>
#include<fstream>
using namespace std;
struct Student {
int roll_no;
string name;
};
int main() {
ofstream wf("student.dat", ios::out | ios::binary);
if(!wf) {
cout << "Cannot open file!" << endl;
return 1;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Binary file Example Code
#include<iostream>
#include<fstream>
using namespace std;
struct Student {
int roll_no;
string name;
};
int main() {
ofstream wf("student.dat", ios::out | ios::binary);
if(!wf) {
cout << "Cannot open file!" << endl;
return 1;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Student wstu[3];
wstu[0].roll_no = 1;
wstu[0].name = "Ram";
wstu[1].roll_no = 2;
wstu[1].name = "Shyam";
wstu[2].roll_no = 3;
wstu[2].name = "Madhu";
for(int i = 0; i < 3; i++)
wf.write((char *) &wstu[i], sizeof(Student));
wf.close();
if(!wf.good()) {
cout << "Error occurred at writing time!" <<
endl;
return 1;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
cout<<"Student's Details:"<<endl;
for(int i=0; i < 3; i++) {
cout << "Roll No: " << s1[i].roll_no << endl;
cout << "Name: " << s1[i].name << endl;
cout << endl;
}
return 0;
}
Student s1[3];
s1[0].roll_no = 1;
s1[0].name = "Ram";
s1[1].roll_no = 2;
s1[1].name = "Shyam";
s1[2].roll_no = 3;
s1[2].name = "Madhu";
for(int i = 0; i < 3; i++)
wf.write((char *) &s1[i], sizeof(Student));
wf.close();
if(!wf.good()) {
cout << "Error occurred at writing time!" << endl;
return 1; }
#include<iostream>
#include<fstream>
using namespace std;
struct Student {
int roll_no;
string name;
};
int main() {
ofstream wf("student.dat", ios::out | ios::binary);
if(!wf) {
cout << "Cannot open file!" << endl;
return 1;
}
UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
Reference
• https://cplusplus.com/reference/iostream/
• https://www.programiz.com/cpp-
programming/library-function/iostream
• https://www.javatpoint.com/what-is-include-
iostream-in-cpp
• https://en.cppreference.com/w/cpp/io/manip
• https://icarus.cs.weber.edu/~dab/cs1410/textbook/11.
Operators/io_overload.html#:~:text=Programmers%
20frequently%20overload%20the%20inserter,functi
on%20follows%20a%20fixed%20pattern.
• https://www.tutorialspoint.com/writing-a-binary-
file-in-cplusplus
In this Unit 5 we discussed the following
topics,
UNIT 5 : IOstreams and Files
5.1 IOstreams
5.2 Manipulators
5.3 overloading Inserters(<<) and
Extractors(>>)
5.4 Sequential and Random files
5.5 writing and reading objects into/from
files
5.6 binary files
CSE2001 Object Oriented Programming with C++
UNIT 5 : IOstreams and Files
C++ IOSTREAMS and Files OOPs using Adv C++

More Related Content

Similar to C++ IOSTREAMS and Files OOPs using Adv C++

System programmin practical file
System programmin practical fileSystem programmin practical file
System programmin practical file
Ankit Dixit
 
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...
Codemotion
 
C programming session 14
C programming session 14C programming session 14
C programming session 14
Vivek Singh
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
Shyam Gupta
 
Managing console of I/o operations & working with files
Managing console of I/o operations & working with filesManaging console of I/o operations & working with files
Managing console of I/o operations & working with files
lalithambiga kamaraj
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdf
Tigabu Yaya
 
CTE 313 - Lecture 3.pptx
CTE 313 - Lecture 3.pptxCTE 313 - Lecture 3.pptx
CTE 313 - Lecture 3.pptx
OduniyiAdebola
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
zynofustechnology
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
YOGESH SINGH
 
File Handling in c++
File Handling in c++File Handling in c++
File Handling in c++
SoniKirtan
 
Learn python
Learn pythonLearn python
Learn python
Rokibul Islam
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Whole c++ lectures ITM1 Th
Whole c++ lectures ITM1 ThWhole c++ lectures ITM1 Th
Whole c++ lectures ITM1 Th
Aram Mohammed
 
MODULE 1.pptx
MODULE 1.pptxMODULE 1.pptx
MODULE 1.pptx
KPDDRAVIDIAN
 
Linker and loader upload
Linker and loader   uploadLinker and loader   upload
Linker and loader upload
Bin Yang
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
Umesh Nikam
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptx
VishuSaini22
 

Similar to C++ IOSTREAMS and Files OOPs using Adv C++ (20)

System programmin practical file
System programmin practical fileSystem programmin practical file
System programmin practical file
 
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...
Fernando Arnaboldi - Exposing Hidden Exploitable Behaviors Using Extended Dif...
 
C programming session 14
C programming session 14C programming session 14
C programming session 14
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Managing console of I/o operations & working with files
Managing console of I/o operations & working with filesManaging console of I/o operations & working with files
Managing console of I/o operations & working with files
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdf
 
CTE 313 - Lecture 3.pptx
CTE 313 - Lecture 3.pptxCTE 313 - Lecture 3.pptx
CTE 313 - Lecture 3.pptx
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
File Handling in c++
File Handling in c++File Handling in c++
File Handling in c++
 
Learn python
Learn pythonLearn python
Learn python
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Whole c++ lectures ITM1 Th
Whole c++ lectures ITM1 ThWhole c++ lectures ITM1 Th
Whole c++ lectures ITM1 Th
 
MODULE 1.pptx
MODULE 1.pptxMODULE 1.pptx
MODULE 1.pptx
 
Linker and loader upload
Linker and loader   uploadLinker and loader   upload
Linker and loader upload
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptx
 

Recently uploaded

Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
Introduction to AI Safety (public presentation).pptx
Introduction to AI Safety (public presentation).pptxIntroduction to AI Safety (public presentation).pptx
Introduction to AI Safety (public presentation).pptx
MiscAnnoy1
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
Roger Rozario
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
GauravCar
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
Las Vegas Warehouse
 
Software Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.pptSoftware Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.ppt
TaghreedAltamimi
 
john krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptxjohn krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptx
Madan Karki
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 

Recently uploaded (20)

Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
Introduction to AI Safety (public presentation).pptx
Introduction to AI Safety (public presentation).pptxIntroduction to AI Safety (public presentation).pptx
Introduction to AI Safety (public presentation).pptx
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
 
Software Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.pptSoftware Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.ppt
 
john krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptxjohn krisinger-the science and history of the alcoholic beverage.pptx
john krisinger-the science and history of the alcoholic beverage.pptx
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 

C++ IOSTREAMS and Files OOPs using Adv C++

  • 1. Course Code CSE2001 Object Oriented Programming with C++ Type LTP Credits 4 UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++
  • 2. Object Oriented Programming with C++ Course Code: CSE2001 UNIT 5 : CSE2001 IOstreams and Fi les UNIT 5 : IOstreams and Files  5.1 IOstreams 5.2 Manipulators 5.3 overloading Inserters(<<) and Extractors(>>) 5.4 Sequential and Random files 5.5 writing and reading objects into/from files 5.6 binary files
  • 3. C++ Files and Streams A stream in simple words is flow of data. C++ views each files as a stream. The operations associated with files are read and write C++ provides various classes to support these operations. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 4. Streams • Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) – it acts as a buffer between the data source and destination • Input stream: a stream that provides input to a program – System.in is an input stream • Output stream: a stream that accepts output from a program – System.out is an output stream • A stream connects a program to an I/O object – System.out connects a program to the screen – System.in connects a program to the keyboard UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 5. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 6. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 7. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 8. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 9. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 10. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 11. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 12. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 13. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 14. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 15. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 16. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 17. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 18. Binary Versus Text Files • All data and programs are ultimately just zeros and ones – each digit can have one of two values, hence binary – bit is one binary digit – byte is a group of eight bits • Text files: the bits represent printable characters – one byte per character for ASCII, the most common code – for example,CPP source files are text files – so is any file created with a "text editor" • Binary files: the bits represent other types of encoded information, such as executable instructions or numeric data – these files are easily read by the computer but not humans – they are not "printable" files • actually, you can print them, but they will be unintelligible • "printable" means "easily readable by humans when printed" UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 19. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 20. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 21. To perform file processing in C++, the header files essential are <iostream> and <fstream> <fstream> includes <ifstream> and <ofstream> ios is the base class for all these classes. These classes provide several member functions that perform input/output operations. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 22. Abbreviated C++ class hierarchy for input output streams UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 23. iostream -- contains basic information required for all stream I/O operations fstream -- contains information for performing file I/O operations iomanip -- contains information useful for performing formatted I/O with parameterized stream manipulators UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 24. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 25. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 26. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 27. How to open a file in C++ ? ofstream outFile(“sample.dat”, ios:out) OR ofstream outFile; outFile.open(“sample.dat”, ios:out) UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 28. How to close a file in C++? The file is closed implicitly when a destructor for the corresponding object is called OR by using member function close: outFile.close(); UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 29. File Open Modes ios:: app - (append) write all output to the end of file ios:: ate - data can be written anywhere in the file ios:: binary - read/write data in binary format ios:: in - (input) open a file for input ios::out - (output) open afile for output ios: trunc -(truncate) discard the files’ contents if it exists UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 30. File Open Modes ios::nocreate - if the file does NOT exists, the open operation fails ios::noreplace - if the file exists, the open operation fails UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 31. Reading and printing a sequential file inFile >> var1 >> var2 >> var3 outFile<<“Name: “<<var1<<“Age : “<<var2<<endl; UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 32. 167 File position pointer <istream> and <ostream> classes provide member functions for repositioning the file pointer (the byte number of the next byte in the file to be read or to be written.) These member functions are: seekg (seek get) for istream class seekp (seek put) for ostream class
  • 33. Examples of moving a file pointer inFile.seekg(0) - repositions the file get pointer to the beginning of the file inFile.seekg(n, ios:beg) - repositions the file get pointer to the n-th byte of the file inFile.seekg(m, ios:end) -repositions the file get pointer to the m-th byte from the end of file inFile.seekg(0, ios:end) - repositions the file get pointer to the end of the file The same operations can be performed with <ostream> function member seekp. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 34. Member functions tellg() and tellp() Member functions tellg and tellp are provided to return the current locations of the get and put pointers, respectively. long location = inFile.tellg(); To move the pointer relative to the current location use ios::cur inFile.seekg(n, ios::cur) - moves the file get pointer n bytes forward. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 35. UNIT 5 : IOstreams and Files 5.1 IOstreams  5.2 Manipulators 5.3 overloading Inserters(<<) and Extractors(>>) 5.4 Sequential and Random files 5.5 writing and reading objects into/from files 5.6 binary files CSE2001 Object Oriented Programming with C++ UNIT 5 : IOstreams and Files UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 36. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 37. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 38. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 39. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 40. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 41. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 42. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 43. • Manipulators are helping functions that can modify the input/output stream. • It does not mean that we change the value of a variable, it only modifies the I/O stream using insertion (<<) and extraction (>>) operators. • Manipulators are special functions that can be included in the I/O statement to alter the format parameters of a stream. • Manipulators are operators that are used to format the data display. • To access manipulators, the file iomanip.h should be included in the program. • For example, if we want to print the hexadecimal value of 100 then we can print it as: • cout<<setbase(16)<<100 Types of Manipulators There are various types of manipulators: UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 44. Manipulators without arguments: The most important manipulators defined by the IOStream library are provided below. endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all the output written on the screen or in the file) the output stream. ws: It is defined in istream and is used to ignore the whitespaces in the string sequence. ends: It is also defined in ostream and it inserts a null character into the output stream. It typically works with std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string. flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written on the screen or in the file. Without flush, the output would be the same, but may not appear in real-time. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 45. C++ Stream I/O -- Stream Manipulators C++ provides various stream manipulators that perform formatting tasks. Stream manipulators are defined in <iomanip> These manipulators provide capabilities for setting field widths, setting precision, UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 46. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 47. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 48. C++ Stream I/O -- Stream Manipulators setting and unsetting format flags, flushing streams, inserting a "newline" and flushing output stream, skipping whitespace in input stream UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 49. I/O -- Stream Manipulators setprecision ( )  Select output precision, i.e., number of significant digits to be printed.  Example: cout << setprecision (2) ; // two significant digits UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 50. I/O -- Stream Manipulators setw ( )  Specify the field width (Can be used on input or output, but only applies to next insertion or extraction).  Example: cout << setw (4) ; // field is four positions wide UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 51. UNIT 5 : IOstreams and Files 5.1 IOstreams 5.2 Manipulators  5.3 overloading Inserters(<<) and Extractors(>>) 5.4 Sequential and Random files 5.5 writing and reading objects into/from files 5.6 binary files CSE2001 Object Oriented Programming with C++ UNIT 5 : IOstreams and Files UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 52. 5.3 overloading Inserters(<<) and Extractors(>>) overloading Inserters(<<) • Programmers frequently overload the inserter (or insertion) and extractor (or extraction) operators because they are the main output and input functions for C++ programs. Each function follows a fixed pattern. Example: Int variable; Cin>>variable; Cout<< variable; UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 53. example friend ostream& operator<<(ostream& out, fraction & f) { // format and print member variables of f return out; } friend istream& operator>>(istream& in, fraction & f) { // read member variables of f return in; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 54. • The patterns illustrated here assume that the operator definitions are placed inside the class (i.e., not just prototyped in the class). • We must keep prototypes in the class, but we can move the function bodies out of the class by dropping the friend keyword. • parts that cannot change: Both functions are always implemented as friends •operator<< always returns an ostream reference has an ostream reference for the first parameter operator>> always • returns an istream reference has an istream reference for the first parameter • more flexible parts but still required by the pattern: UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 55. • The second parameter for both operators is always a class reference. The class name is always the class for which the operator is overloaded • programmer specified names: • names for the ostream and istream reference variables • names for the output and input object reference variables • function specific operations: • format and print member variables read values from the input stream into the member variables Both operators always end with a return statement, and the returned value is always the name of the first parameter UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 56. UNIT 5 : IOstreams and Files 5.1 IOstreams 5.2 Manipulators 5.3 overloading Inserters(<<) and Extractors(>>)  5.4 Sequential and Random files 5.5 writing and reading objects into/from files 5.6 binary files CSE2001 Object Oriented Programming with C++ UNIT 5 : IOstreams and Files UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 57. C++ Files and Streams • C++ views each files as a sequence of bytes. • Each file ends with an end-of-file marker. • When a file is opened, an object is created and a stream is associated with the object. • To perform file processing in C++, the header files <iostream.h> and <fstream.h> must be included. • <fstream.> includes <ifstream> and <ofstream> UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 58. 193 5.4 Sequential and Random files Updating a sequential file • Data that is formatted and written to a sequential file cannot be modified easily without the risk of destroying other data in the file. • If we want to modify a record of data, the new data may be longer than the old one and it could overwrite parts of the record following it. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 59. Problems with sequential files Sequential files are inappropriate for so-called “instant access” applications in which a particular record of information must be located immediately. These applications include banking systems, point-of-sale systems, airline reservation systems, (or any data-base system.) UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 60. Random access files • Instant access is possible with random access files. • Individual records of a random access file can be accessed directly (and quickly) without searching many other records. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 61. Sequential and Random files • In a sequential access file, data is accessed in a linear, sequential manner, from start to end. Each read or write operation must follow the previous one. • In contrast, in a random access file, data can be accessed at any point in the file, without having to read through the entire file first • sequential access files Simple and straightforward to implement, with minimal hardware and software requirements. It is inexpensive because it does not necessitate complex indexing or search algorithms. • Because data is stored in a linear fashion and can be accessed predictably, it is extremely efficient for dealing with large data sets. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 62. Parameter Sequential Access Random Access Access Speed Sequential access files are slower compared to random access files since accessing a specific record requires reading through all the previous records in the file Random access files, on the other hand, allow direct access to specific records, resulting in faster access times. Access Method Sequential access files allow access to records in a sequential manner Random access files allow direct access to specific records using an index, record number, or key. Record Ordering Sequential access files store records in a specific order, usually the order in which they were added to the file. Random access files do not have any specific order of storing records. Insertion of New Record Inserting a new record in a sequential access file is relatively easy since new records are added to the end of the file. Random access files may require relocating other records to maintain the order so insertion becomes hard as compared to sequential access. Memory Requirements Sequential access files require less memory than random access files since they do not need to store any indexing information. Random access files require more memory because of indexing information Search Flexibility Search flexibility is limited in sequential access file. Random access files offer higher search flexibility than sequential access files since they allow for direct access to specific records based on various search criteria Record Sizes In sequential access files, record sizes are usually uniform Random access files, record sizes can be variable File Organization Sequential access files are typically organized in a linear fashion Random access files are typically indexed. Examples Text files, Logs Database, Spreadsheet
  • 63. 198 Creating a sequential file // Create a sequential file #include <iostream.h> #include <fstream.h> #include <stdlib.h> int main() { // ofstream constructor opens file ofstream oC( "clients.dat", ios::out ); if ( !oC ) { // overloaded ! operator cerr << "File could not be opened" << endl; exit( 1 ); // prototype in stdlib.h } cout << "Enter the account, name, and balance.n" << "Enter end-of-file to end input.n? "; int account; char name[ 30 ]; float balance; while ( cin >> account >> name >> balance ) { oC<< account << ' ' << name << ' ' << balance << 'n'; cout << "? "; } return 0; // ofstream destructor closes file } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 64. 199 Creating a sequential file // Create a sequential file #include <iostream.h> #include <fstream.h> #include <stdlib.h> int main() { // ofstream constructor opens file ofstream outClientFile( "clients.dat", ios::out ); if ( !outClientFile ) { // overloaded ! operator cerr << "File could not be opened" << endl; exit( 1 ); // prototype in stdlib.h } cout << "Enter the account, name, and balance.n" << "Enter end-of-file to end input.n? "; int account; char name[ 30 ]; float balance; while ( cin >> account >> name >> balance ) { outClientFile << account << ' ' << name << ' ' << balance << 'n'; cout << "? "; } return 0; // ofstream destructor closes file } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 65. 200 Creating a sequential file // Create a sequential file #include <iostream.h> #include <fstream.h> #include <stdlib.h> int main() { // ofstream constructor opens file ofstream outClientFile( "clients.dat", ios::out ); if ( !outClientFile ) { // overloaded ! operator cerr << "File could not be opened" << endl; exit( 1 ); // prototype in stdlib.h } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 66. Sequential file cout << "Enter the account, name, and balance.n" << "Enter end-of-file to end input.n? "; int account; char name[ 30 ]; float balance; while ( cin >> account >> name >> balance ) { outClientFile << account << ' ' << name << ' ' << balance << 'n'; cout << "? "; } return 0; // ofstream destructor closes file } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 67. How to open a file in C++ ? Ofstream outClientFile(“clients.dat”, ios:out) OR Ofstream outClientFile; outClientFile.open(“clients.dat”, ios:out) UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 68. File Open Modes ios:: app - (append) write all output to the end of file ios:: ate - data can be written anywhere in the file ios:: binary - read/write data in binary format ios:: in - (input) open a file for input ios::out - (output) open afile for output ios: trunc -(truncate) discard the files’ contents if it exists UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 69. 204 File Open Modes cont. ios:nocreate - if the file does NOT exists, the open operation fails ios:noreplace - if the file exists, the open operation fails UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 70. 205 How to close a file in C++? The file is closed implicitly when a destructor for the corresponding object is called OR by using member function close: outClientFile.close(); UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 71. 206 Reading and printing a sequential file // Reading and printing a sequential file #include <iostream.h> #include <fstream.h> #include <iomanip.h> #include <stdlib.h> void outputLine( int, const char *, double ); int main() { // ifstream constructor opens the file ifstream inClientFile( "clients.dat", ios::in ); if ( !inClientFile ) { cerr << "File could not be openedn"; exit( 1 ); }
  • 72. int account; char name[ 30 ]; double balance; cout << setiosflags( ios::left ) << setw( 10 ) << "Account" << setw( 13 ) << "Name" << "Balancen"; while ( inClientFile >> account >> name >> balance ) outputLine( account, name, balance ); return 0; // ifstream destructor closes the file } void outputLine( int acct, const char *name, double bal ) { cout << setiosflags( ios::left ) << setw( 10 ) << acct << setw( 13 ) << name << setw( 7 ) << setprecision( 2 ) << resetiosflags( ios::left ) << setiosflags( ios::fixed | ios::showpoint ) << bal << 'n'; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 73. 208 File position pointer <istream> and <ostream> classes provide member functions for repositioning the file pointer (the byte number of the next byte in the file to be read or to be written.) These member functions are: seekg (seek get) for istream class seekp (seek put) for ostream class UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 74. 209 Examples of moving a file pointer inClientFile.seekg(0) - repositions the file get pointer to the beginning of the file inClientFile.seekg(n, ios:beg) - repositions the file get pointer to the n-th byte of the file inClientFile.seekg(m, ios:end) -repositions the file get pointer to the m-th byte from the end of file nClientFile.seekg(0, ios:end) - repositions the file get pointer to the end of the file The same operations can be performed with <ostream> function member seekp. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 75. 210 Member functions tellg() and tellp(). Member functions tellg and tellp are provided to return the current locations of the get and put pointers, respectively. long location = inClientFile.tellg(); To move the pointer relative to the current location use ios:cur inClientFile.seekg(n, ios:cur) - moves the file get pointer n bytes forward. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 76. 211 Updating a sequential file Data that is formatted and written to a sequential file cannot be modified easily without the risk of destroying other data in the file. If we want to modify a record of data, the new data may be longer than the old one and it could overwrite parts of the record following it. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 77. Problems with sequential files • Sequential files are inappropriate for so-called “instant access” applications in which a particular record of information must be located immediately. • These applications include banking systems, point- of-sale systems, airline reservation systems, (or any data-base system.) UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 78. 213 Random access files • Instant access is possible with random access files. • Individual records of a random access file can be accessed directly (and quickly) without searching many other records. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 79. 214 Example of a Program that Creates a Random Access File // Fig. 14.11: clntdata.h // Definition of struct clientData used in #ifndef CLNTDATA_H #define CLNTDATA_H struct clientData { int accountNumber; char lastName[ 15 ]; char firstName[ 10 ]; float balance; }; #endif UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 80. Creating a random access file // Creating a randomly accessed file sequentially #include <iostream.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" int main() { ofstream outCredit( "credit1.dat", ios::out); if ( !outCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 81. 216 clientData blankClient = { 0, "", "", 0.0 }; for ( int i = 0; i < 100; i++ ) outCredit.write (reinterpret_cast<const char *>( &blankClient ), sizeof( clientData ) ); return 0; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 82. 217 <ostream> memebr function write The <ostream> member function write outputs a fixed number of bytes beginning at a specific location in memory to the specific stream. When the stream is associated with a file, the data is written beginning at the location in the file specified by the “put” file pointer. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 83. 218 Writing data randomly to a random file #include <iostream.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" int main() { ofstream outCredit( "credit.dat", ios::ate ); if ( !outCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 84. 219 cout << "Enter account number " << "(1 to 100, 0 to end input)n? "; clientData client; cin >> client.accountNumber; while ( client.accountNumber > 0 && client.accountNumber <= 100 ) { cout << "Enter lastname, firstname, balancen? "; cin >> client.lastName >> client.firstName >> client.balance; UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 85. 220 outCredit.seekp( ( client.accountNumber - 1 ) * sizeof( clientData ) ); outCredit.write( reinterpret_cast<const char *>( &client ), sizeof( clientData ) ); cout << "Enter account numbern? "; cin >> client.accountNumber; } return 0; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 86. 221 Reading data from a random file #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" void outputLine( ostream&, const clientData & ); int main() { ifstream inCredit( "credit.dat", ios::in ); if ( !inCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 87. 222 cout << setiosflags( ios::left ) << setw( 10 ) << "Account" << setw( 16 ) << "Last Name" << setw( 11 ) << "First Name" << resetiosflags( ios::left ) << setw( 10 ) << "Balance" << endl; clientData client; inCredit.read( reinterpret_cast<char *>( &client ), sizeof( clientData ) ); UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 88. 223 while ( inCredit && !inCredit.eof() ) { if ( client.accountNumber != 0 ) outputLine( cout, client ); inCredit.read( reinterpret_cast<char *>( &client ), sizeof( clientData ) ); } return 0; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 89. 224 void outputLine( ostream &output, const clientData &c ) { output << setiosflags( ios::left ) << setw( 10 ) << c.accountNumber << setw( 16 ) << c.lastName << setw( 11 ) << c.firstName << setw( 10 ) << setprecision( 2 ) << resetiosflags( ios::left ) << setiosflags( ios::fixed | ios::showpoint ) << c.balance << 'n'; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 90. The <istream> function read inCredit.read (reinterpret_cast<char *>(&client), sizeof(clientData)); The <istream> function inputs a specified (by sizeof(clientData)) number of bytes from the current position of the specified stream into an object. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 91. 226 Example of a Program that Creates a Random Access File /// Definition of struct clientData used in #ifndef CLNTDATA_H #define CLNTDATA_H struct clientData { int accountNumber; char lastName[ 15 ]; char firstName[ 10 ]; float balance; }; #endif UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 92. 227 Creating a random access file // Creating a randomly accessed file sequentially #include <iostream.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" int main() { ofstream outCredit( "credit1.dat", ios::out); if ( !outCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 93. 228 clientData blankClient = { 0, "", "", 0.0 }; for ( int i = 0; i < 100; i++ ) outCredit.write (reinterpret_cast<const char *>( &blankClient ), sizeof( clientData ) ); return 0; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 94. 229 <ostream> member function write The <ostream> member function write outputs a fixed number of bytes beginning at a specific location in memory to the specific stream. When the stream is associated with a file, the data is written beginning at the location in the file specified by the “put” file pointer. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 95. 230 The write function expects a first argument of type const char *, hence we used the reinterpret_cast <const char *> to convert the address of the blankClient to a const char*. The second argument of write is an integer of type size_t specifying the number of bytes to written. Thus the sizeof( clientData ). UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 96. 231 Writing data randomly to a random file #include <iostream.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" int main() { ofstream outCredit( "credit.dat", ios::ate ); if ( !outCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 97. cout << "Enter account number " << "(1 to 100, 0 to end input)n? "; clientData client; cin >> client.accountNumber; while ( client.accountNumber > 0 && client.accountNumber <= 100 ) { cout << "Enter lastname, firstname, balancen? "; cin >> client.lastName >> client.firstName >> client.balance; UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 98. outCredit.seekp( ( client.accountNumber - 1 ) * sizeof( clientData ) ); outCredit.write( reinterpret_cast<const char *>( &client ), sizeof( clientData ) ); cout << "Enter account numbern? "; cin >> client.accountNumber; } return 0; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 99. 234 Reading data from a random file #include <iostream> #include <iomanip.h> #include <fstream> #include <stdlib.h> #include "clntdata.h" void outputLine( ostream&, const clientData & ); int main() { ifstream inCredit( "credit.dat", ios::in ); if ( !inCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 100. cout << setiosflags( ios::left ) << setw( 10 ) << "Account" << setw( 16 ) << "Last Name" << setw( 11 ) << "First Name" << resetiosflags( ios::left ) << setw( 10 ) << "Balance" << endl; clientData client; inCredit.read( reinterpret_cast<char *>( &client ), sizeof( clientData ) ); UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 101. while ( inCredit && !inCredit.eof() ) { if ( client.accountNumber != 0 ) outputLine( cout, client ); inCredit.read( reinterpret_cast<char *>( &client ), sizeof( clientData ) ); } return 0; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 102. void outputLine( ostream &output, const clientData &c ) { output << setiosflags( ios::left ) << setw( 10 ) << c.accountNumber << setw( 16 ) << c.lastName << setw( 11 ) << c.firstName << setw( 10 ) << setprecision( 2 ) << resetiosflags( ios::left ) << setiosflags( ios::fixed | ios::showpoint ) << c.balance << 'n'; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 103. 238 The <istream> function read inCredit.read (reinterpret_cast<char *>(&client), sizeof(clientData)); The <istream> function inputs a specified (by sizeof(clientData)) number of bytes from the current position of the specified stream into an object. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 104. Stream I/O Format State Flags ios::showpointwhen set, show trailing decimal point and zeros ios::showpos when set, show the + sign before positive numbers ios::basefield ios::dec use base ten ios::oct use base eight ios::hex use base sixteen 239 UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 105. Stream I/O Format State Flags ios::floatfield ios::fixed use fixed number of digits ios::scientific use "scientific" notation ios::adjustfield ios::left use left justification ios::right use right justification ios::internal left justify the sign, but right justify the value 240 UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 106. .setf ( )  Allows the setting of an I/O stream format flag.  Examples: // To show the + sign in front of positive numbers cout.setf (ios::showpos) ; // To output the number in hexadecimal cout.setf (ios::hex, ios::basefield) ; 241 UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 107. UNIT 5 : IOstreams and Files 5.1 IOstreams 5.2 Manipulators 5.3 overloading Inserters(<<) and Extractors(>>) 5.4 Sequential and Random files 5.5 writing and reading objects into/from files 5.6 BINARY FILES CSE2001 Object Oriented Programming with C++ UNIT 5 : IOstreams and Files UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 108. Need for FILES in C++ • Data is very important. Every organization depends on its data for continuing its business operations. • If the data is lost, the organization has to be closed. • This is the reason computers are primarily created for handling data, especially for storing and retrieving data. • In later days, programs are developed to process the data that is stored in the computer. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 109. C++ FILES APPLICATION • To store data in a computer, we need files. • For example, we can store employee data like employee number, name and salary in a file in the computer and later use it whenever we want. • Similarly, we can store student data like student roll number, name and marks in the computer. In computers’ view, a file is nothing but collection of data that is available to a program. • Once we store data in a computer file, we can retrieve it and use it depending on our requirements. • UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 110. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 111. ADVANTAGES OF STORING A DATA IN A FILE • When the data is stored in a file, it is stored permanently. • This means that even though the computer is switched off, the data is not removed from the memory since the file is stored on hard disk or CD. • This file data can be utilized later, whenever required. • It is possible to update the file data. • For example, we can add new data to the existing file, delete unnecessary data from the file and modify the available data of the file. This makes the file more useful. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 112. ADVANTAGES OF STORING A DATA IN A FILE • Once the data is stored in a file, the same data can be shared by various programs. • For example, once employee data is stored in a file, it can be used in a program to calculate employees’ net salaries or in another program to calculate income tax payable by the employees. • Files are highly useful to store huge amount of data. For example, voters’ list or census data. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 113. TYPES OF FILES • In Python, there are two types of files. • They are:  Text files  Binary files • Text files store the data in the form of characters. For example, if we store employee name “Ganesh”, it will be stored as 6 characters and the employee salary 8900.75 is stored as 7 characters. • Text files are used to store characters or strings. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 114. TYPES OF FILES • Binary files store entire data in the form of bytes, i.e. a group of 8 bits each. • For example, a character is stored as a byte and an integer is stored in the form of 8 bytes (on a 64 bit machine). When the data is retrieved from the binary file, the programmer can retrieve the data as bytes. • Binary files can be used to store text, images, audio and video. Image files are generally available in .jpg, .gif or .png formats. • We cannot use text files to store images as the images do not contain characters. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 115. TYPES OF FILES • On the other hand, images contain pixels which are minute dots with which the picture is composed of. • Each pixel can be represented by a bit, i.e. either 1 or 0. Since these bits can be handled by binary files, we can say that they are highly suitable to store images. It is very important to know how to create files, store data in the files and retrieve the data from the files. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 116. MODES OF FILES UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 117. Binary file • Binary file is a file with data stored in raw format, the way it is stored in memory. • For example, numbers are stored in binary in memory. • They are not converted to text (ASCII characters) when writing to binary file. • The data in binary format is not human readable and cannot be read or modified using text editors. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 118. • A binary file is a file whose content is in a binary format consisting of a series of sequential bytes, each of which is eight bits in length. • The content must be interpreted by a program or a hardware processor that understands in advance exactly how that content is formatted and how to read the data. Binary file UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 119. • For example, only Microsoft Word and certain other word processing programs can interpret the formatting information in a Word document. • Executable files, compiled programs, SAS and SPSS system files, spreadsheets, compressed files, and graphic (image) files are all examples of binary files. Binary file UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 120. Binary file • To write a binary file in C++ use write method. It is used to write a given number of bytes on the given stream, starting at the position of the "put" pointer. • The file is extended if the put pointer is current at the end of the file. If this pointer points into the middle of the file, characters in the file are overwritten with the new data. • If any error has occurred during writing in the file, the stream is placed in an error state. UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 121. Binary file • Syntax of write method • ostream& write(const char*, int); UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 122. Binary file Example Code #include<iostream> #include<fstream> using namespace std; struct Student { int roll_no; string name; }; int main() { ofstream wf("student.dat", ios::out | ios::binary); if(!wf) { cout << "Cannot open file!" << endl; return 1; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 123. Binary file Example Code #include<iostream> #include<fstream> using namespace std; struct Student { int roll_no; string name; }; int main() { ofstream wf("student.dat", ios::out | ios::binary); if(!wf) { cout << "Cannot open file!" << endl; return 1; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 124. Student wstu[3]; wstu[0].roll_no = 1; wstu[0].name = "Ram"; wstu[1].roll_no = 2; wstu[1].name = "Shyam"; wstu[2].roll_no = 3; wstu[2].name = "Madhu"; for(int i = 0; i < 3; i++) wf.write((char *) &wstu[i], sizeof(Student)); wf.close(); if(!wf.good()) { cout << "Error occurred at writing time!" << endl; return 1; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 125. cout<<"Student's Details:"<<endl; for(int i=0; i < 3; i++) { cout << "Roll No: " << s1[i].roll_no << endl; cout << "Name: " << s1[i].name << endl; cout << endl; } return 0; } Student s1[3]; s1[0].roll_no = 1; s1[0].name = "Ram"; s1[1].roll_no = 2; s1[1].name = "Shyam"; s1[2].roll_no = 3; s1[2].name = "Madhu"; for(int i = 0; i < 3; i++) wf.write((char *) &s1[i], sizeof(Student)); wf.close(); if(!wf.good()) { cout << "Error occurred at writing time!" << endl; return 1; } #include<iostream> #include<fstream> using namespace std; struct Student { int roll_no; string name; }; int main() { ofstream wf("student.dat", ios::out | ios::binary); if(!wf) { cout << "Cannot open file!" << endl; return 1; } UNIT 5_ PART 2 : IOstreams and Fi les OOPs using C++ by Dr MK Jayanthi Kannan
  • 126. Reference • https://cplusplus.com/reference/iostream/ • https://www.programiz.com/cpp- programming/library-function/iostream • https://www.javatpoint.com/what-is-include- iostream-in-cpp • https://en.cppreference.com/w/cpp/io/manip • https://icarus.cs.weber.edu/~dab/cs1410/textbook/11. Operators/io_overload.html#:~:text=Programmers% 20frequently%20overload%20the%20inserter,functi on%20follows%20a%20fixed%20pattern. • https://www.tutorialspoint.com/writing-a-binary- file-in-cplusplus
  • 127. In this Unit 5 we discussed the following topics, UNIT 5 : IOstreams and Files 5.1 IOstreams 5.2 Manipulators 5.3 overloading Inserters(<<) and Extractors(>>) 5.4 Sequential and Random files 5.5 writing and reading objects into/from files 5.6 binary files CSE2001 Object Oriented Programming with C++ UNIT 5 : IOstreams and Files