SlideShare a Scribd company logo
C++ Files and
Streams
1
2
Learning Objectives
C++ I/O streams.
Reading and writing sequential files.
Reading and writing random access files.
3
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>
4
Creating a sequential file
// Fig. 14.4: fig14_04.cpp D&D p.708
// 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
}
5
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
}
6
Question.
What does the above program do?
7
How to open a file in C++ ?
Ofstream outClientFile(“clients.dat”, ios:out)
OR
Ofstream outClientFile;
outClientFile.open(“clients.dat”, ios:out)
8
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
9
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
10
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();
11
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 );
}
12
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';
}
13
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
14
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.
15
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.
16
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.
17
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.)
18
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.
19
Example of a Program that
Creates a Random Access File
// Fig. 14.11: clntdata.h
// Definition of struct clientData used in
// Figs. 14.11, 14.12, 14.14 and 14.15.
#ifndef CLNTDATA_H
#define CLNTDATA_H
struct clientData {
int accountNumber;
char lastName[ 15 ];
char firstName[ 10 ];
float balance;
};
#endif
20
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 );
}
21
clientData blankClient = { 0, "", "", 0.0 };
for ( int i = 0; i < 100; i++ )
outCredit.write
(reinterpret_cast<const char *>( &blankClient ),
sizeof( clientData ) );
return 0;
}
22
<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.
23
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 ).
24
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 );
}
25
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;
26
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;
}
27
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 );
}
28
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 ) );
29
while ( inCredit && !inCredit.eof() ) {
if ( client.accountNumber != 0 )
outputLine( cout, client );
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );
}
return 0;
}
30
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';
}
31
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.

More Related Content

PPTX
Files in c++
PPSX
Files in c++
PPT
17 files and streams
PDF
C++ Files and Streams
PPT
File in cpp 2016
PPT
File handling in C++
PPTX
Pf cs102 programming-8 [file handling] (1)
PPT
Files in c++ ppt
Files in c++
Files in c++
17 files and streams
C++ Files and Streams
File in cpp 2016
File handling in C++
Pf cs102 programming-8 [file handling] (1)
Files in c++ ppt

What's hot (19)

PDF
file handling c++
PPT
working file handling in cpp overview
PDF
Filehadnling
PPTX
File handling in c++
PPT
File handling in_c
PPTX
Stream classes in C++
PPT
file handling, dynamic memory allocation
PPT
Cpp file-handling
PPTX
Filesin c++
PPT
Filehandlinging cp2
PPT
File handling
PDF
Filesinc 130512002619-phpapp01
PPTX
basics of file handling
PDF
08. handling file streams
PPT
File Handling In C++(OOPs))
file handling c++
working file handling in cpp overview
Filehadnling
File handling in c++
File handling in_c
Stream classes in C++
file handling, dynamic memory allocation
Cpp file-handling
Filesin c++
Filehandlinging cp2
File handling
Filesinc 130512002619-phpapp01
basics of file handling
08. handling file streams
File Handling In C++(OOPs))
Ad

Similar to C++ files and streams (20)

PPT
hasbngclic687.ppt
DOCX
Exmaples of file handling
PDF
Files and streams
PPT
Java Input Output and File Handling
PPTX
Introduction to files management systems
PPT
Sample file processing
PDF
Chpater29 operation-on-file
PPTX
File_Handling_in_CPP (1).ppthydyryryryryx
PPT
PL-II Lecture19 oop in c++ pyaray bachon .ppt
PPTX
File & Exception Handling in C++.pptx
DOCX
File handling in c++
PPTX
Basics of file handling
PPTX
working with files
PPTX
OBJECT ORIENTED PROGRAMMING IN C++ BASIC AND FUNDAMENTAL CONCEPT OF PROG
PPT
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
PPTX
Cs1123 10 file operations
PPT
7 Data File Handling
PPT
file
PPTX
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
hasbngclic687.ppt
Exmaples of file handling
Files and streams
Java Input Output and File Handling
Introduction to files management systems
Sample file processing
Chpater29 operation-on-file
File_Handling_in_CPP (1).ppthydyryryryryx
PL-II Lecture19 oop in c++ pyaray bachon .ppt
File & Exception Handling in C++.pptx
File handling in c++
Basics of file handling
working with files
OBJECT ORIENTED PROGRAMMING IN C++ BASIC AND FUNDAMENTAL CONCEPT OF PROG
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
Cs1123 10 file operations
7 Data File Handling
file
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Ad

More from krishna partiwala (8)

PPTX
inheritance
PPT
data file handling
PPTX
Information system
PPTX
impact of information technology on society
PPTX
Operating System
PPTX
Data structure
PPTX
Database management system
inheritance
data file handling
Information system
impact of information technology on society
Operating System
Data structure
Database management system

Recently uploaded (20)

PDF
Facade & Landscape Lighting Techniques and Trends.pptx.pdf
PPTX
areprosthodontics and orthodonticsa text.pptx
PDF
ALDO ROSSI AND MICHAEL GRAVES THEORY OF DESIGN-02 , PRESENTATION _TUSHARECHPL...
PPTX
building Planning Overview for step wise design.pptx
DOCX
actividad 20% informatica microsoft project
PDF
GREEN BUILDING MATERIALS FOR SUISTAINABLE ARCHITECTURE AND BUILDING STUDY
PPTX
HPE Aruba-master-icon-library_052722.pptx
PDF
10 Real World Lessons and 4 Practical Tips for Large Group LSP Method
PDF
Emailing DDDX-MBCaEiB.pdf DDD_Europe_2022_Intro_to_Context_Mapping_pdf-165590...
PDF
Integrated-2D-and-3D-Animation-Bridging-Dimensions-for-Impactful-Storytelling...
PPT
Package Design Design Kit 20100009 PWM IC by Bee Technologies
PDF
The Advantages of Working With a Design-Build Studio
PPTX
Introduction to Pathology.pptx 112233445566
PPTX
YV PROFILE PROJECTS PROFILE PRES. DESIGN
PPTX
BSCS lesson 3.pptxnbbjbb mnbkjbkbbkbbkjb
PPTX
KOTA LAMA BANYUMAS.pptxxxxxxxxxxxxxxxxxxxx
DOCX
The story of the first moon landing.docx
PPT
Machine printing techniques and plangi dyeing
PDF
SEVA- Fashion designing-Presentation.pdf
PPTX
Complete Guide to Microsoft PowerPoint 2019 – Features, Tools, and Tips"
Facade & Landscape Lighting Techniques and Trends.pptx.pdf
areprosthodontics and orthodonticsa text.pptx
ALDO ROSSI AND MICHAEL GRAVES THEORY OF DESIGN-02 , PRESENTATION _TUSHARECHPL...
building Planning Overview for step wise design.pptx
actividad 20% informatica microsoft project
GREEN BUILDING MATERIALS FOR SUISTAINABLE ARCHITECTURE AND BUILDING STUDY
HPE Aruba-master-icon-library_052722.pptx
10 Real World Lessons and 4 Practical Tips for Large Group LSP Method
Emailing DDDX-MBCaEiB.pdf DDD_Europe_2022_Intro_to_Context_Mapping_pdf-165590...
Integrated-2D-and-3D-Animation-Bridging-Dimensions-for-Impactful-Storytelling...
Package Design Design Kit 20100009 PWM IC by Bee Technologies
The Advantages of Working With a Design-Build Studio
Introduction to Pathology.pptx 112233445566
YV PROFILE PROJECTS PROFILE PRES. DESIGN
BSCS lesson 3.pptxnbbjbb mnbkjbkbbkbbkjb
KOTA LAMA BANYUMAS.pptxxxxxxxxxxxxxxxxxxxx
The story of the first moon landing.docx
Machine printing techniques and plangi dyeing
SEVA- Fashion designing-Presentation.pdf
Complete Guide to Microsoft PowerPoint 2019 – Features, Tools, and Tips"

C++ files and streams

  • 2. 2 Learning Objectives C++ I/O streams. Reading and writing sequential files. Reading and writing random access files.
  • 3. 3 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>
  • 4. 4 Creating a sequential file // Fig. 14.4: fig14_04.cpp D&D p.708 // 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 }
  • 5. 5 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 }
  • 6. 6 Question. What does the above program do?
  • 7. 7 How to open a file in C++ ? Ofstream outClientFile(“clients.dat”, ios:out) OR Ofstream outClientFile; outClientFile.open(“clients.dat”, ios:out)
  • 8. 8 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
  • 9. 9 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
  • 10. 10 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();
  • 11. 11 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 ); }
  • 12. 12 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'; }
  • 13. 13 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
  • 14. 14 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.
  • 15. 15 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.
  • 16. 16 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.
  • 17. 17 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.)
  • 18. 18 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.
  • 19. 19 Example of a Program that Creates a Random Access File // Fig. 14.11: clntdata.h // Definition of struct clientData used in // Figs. 14.11, 14.12, 14.14 and 14.15. #ifndef CLNTDATA_H #define CLNTDATA_H struct clientData { int accountNumber; char lastName[ 15 ]; char firstName[ 10 ]; float balance; }; #endif
  • 20. 20 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 ); }
  • 21. 21 clientData blankClient = { 0, "", "", 0.0 }; for ( int i = 0; i < 100; i++ ) outCredit.write (reinterpret_cast<const char *>( &blankClient ), sizeof( clientData ) ); return 0; }
  • 22. 22 <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.
  • 23. 23 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 ).
  • 24. 24 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 ); }
  • 25. 25 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;
  • 26. 26 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; }
  • 27. 27 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 ); }
  • 28. 28 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 ) );
  • 29. 29 while ( inCredit && !inCredit.eof() ) { if ( client.accountNumber != 0 ) outputLine( cout, client ); inCredit.read( reinterpret_cast<char *>( &client ), sizeof( clientData ) ); } return 0; }
  • 30. 30 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'; }
  • 31. 31 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.