SlideShare a Scribd company logo
1 of 30
CPSC 231 D.H. C++ File
Processing
1
Learning Objectives
 C++ I/O streams.
 Reading and writing sequential files.
 Reading and writing random access files.
CPSC 231 D.H. C++ File
Processing
2
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>
CPSC 231 D.H. C++ File
Processing
3
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
}
CPSC 231 D.H. C++ File
Processing
4
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
}
CPSC 231 D.H. C++ File
Processing
5
Question.
 What does the above program do?
CPSC 231 D.H. C++ File
Processing
6
How to open a file in C++ ?
Ofstream outClientFile(“clients.dat”, ios:out)
OR
Ofstream outClientFile;
outClientFile.open(“clients.dat”, ios:out)
CPSC 231 D.H. C++ File
Processing
7
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
CPSC 231 D.H. C++ File
Processing
8
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
CPSC 231 D.H. C++ File
Processing
9
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();
CPSC 231 D.H. C++ File
Processing
10
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 );
}
CPSC 231 D.H. C++ File
Processing
11
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';
}
CPSC 231 D.H. C++ File
Processing
12
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
CPSC 231 D.H. C++ File
Processing
13
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.
CPSC 231 D.H. C++ File
Processing
14
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.
CPSC 231 D.H. C++ File
Processing
15
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.
CPSC 231 D.H. C++ File
Processing
16
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.)
CPSC 231 D.H. C++ File
Processing
17
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.
CPSC 231 D.H. C++ File
Processing
18
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
CPSC 231 D.H. C++ File
Processing
19
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 );
}
CPSC 231 D.H. C++ File
Processing
20
clientData blankClient = { 0, "", "", 0.0 };
for ( int i = 0; i < 100; i++ )
outCredit.write
(reinterpret_cast<const char *>( &blankClient ),
sizeof( clientData ) );
return 0;
}
CPSC 231 D.H. C++ File
Processing
21
<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.
CPSC 231 D.H. C++ File
Processing
22
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 ).
CPSC 231 D.H. C++ File
Processing
23
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 );
}
CPSC 231 D.H. C++ File
Processing
24
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;
CPSC 231 D.H. C++ File
Processing
25
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;
}
CPSC 231 D.H. C++ File
Processing
26
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 );
}
CPSC 231 D.H. C++ File
Processing
27
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 ) );
CPSC 231 D.H. C++ File
Processing
28
while ( inCredit && !inCredit.eof() ) {
if ( client.accountNumber != 0 )
outputLine( cout, client );
inCredit.read( reinterpret_cast<char *>( &client ),
sizeof( clientData ) );
}
return 0;
}
CPSC 231 D.H. C++ File
Processing
29
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';
}
CPSC 231 D.H. C++ File
Processing
30
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

Similar to hasbngclic687.ppt

Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Abdullah khawar
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 
Chpater29 operation-on-file
Chpater29 operation-on-fileChpater29 operation-on-file
Chpater29 operation-on-fileDeepak Singh
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxRutujaTandalwade
 
File handling in_c
File handling in_cFile handling in_c
File handling in_csanya6900
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
Build process in ST Visual Develop
Build process in ST Visual DevelopBuild process in ST Visual Develop
Build process in ST Visual DevelopGourav Kumar
 
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeksBeginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeksJinTaek Seo
 
file handling final3333.pptx
file handling final3333.pptxfile handling final3333.pptx
file handling final3333.pptxradhushri
 
Sample file processing
Sample file processingSample file processing
Sample file processingIssay Meii
 
File handling complete programs in c++
File handling complete programs in c++File handling complete programs in c++
File handling complete programs in c++zain ul hassan
 
Working with file(35,45,46)
Working with file(35,45,46)Working with file(35,45,46)
Working with file(35,45,46)Dishant Modi
 
Files in c
Files in cFiles in c
Files in cTanujaA3
 

Similar to hasbngclic687.ppt (20)

Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
How c/c++ works
How c/c++ worksHow c/c++ works
How c/c++ works
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
17 files and streams
17 files and streams17 files and streams
17 files and streams
 
Chpater29 operation-on-file
Chpater29 operation-on-fileChpater29 operation-on-file
Chpater29 operation-on-file
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
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
 
Build process in ST Visual Develop
Build process in ST Visual DevelopBuild process in ST Visual Develop
Build process in ST Visual Develop
 
working with files
working with filesworking with files
working with files
 
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeksBeginning direct3d gameprogrammingcpp02_20160324_jintaeks
Beginning direct3d gameprogrammingcpp02_20160324_jintaeks
 
file handling final3333.pptx
file handling final3333.pptxfile handling final3333.pptx
file handling final3333.pptx
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Sample file processing
Sample file processingSample file processing
Sample file processing
 
File handling complete programs in c++
File handling complete programs in c++File handling complete programs in c++
File handling complete programs in c++
 
Working with file(35,45,46)
Working with file(35,45,46)Working with file(35,45,46)
Working with file(35,45,46)
 
Beyond the page
Beyond the pageBeyond the page
Beyond the page
 
Files in c
Files in cFiles in c
Files in c
 

Recently uploaded

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

hasbngclic687.ppt

  • 1. CPSC 231 D.H. C++ File Processing 1 Learning Objectives  C++ I/O streams.  Reading and writing sequential files.  Reading and writing random access files.
  • 2. CPSC 231 D.H. C++ File Processing 2 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>
  • 3. CPSC 231 D.H. C++ File Processing 3 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 }
  • 4. CPSC 231 D.H. C++ File Processing 4 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 }
  • 5. CPSC 231 D.H. C++ File Processing 5 Question.  What does the above program do?
  • 6. CPSC 231 D.H. C++ File Processing 6 How to open a file in C++ ? Ofstream outClientFile(“clients.dat”, ios:out) OR Ofstream outClientFile; outClientFile.open(“clients.dat”, ios:out)
  • 7. CPSC 231 D.H. C++ File Processing 7 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
  • 8. CPSC 231 D.H. C++ File Processing 8 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
  • 9. CPSC 231 D.H. C++ File Processing 9 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();
  • 10. CPSC 231 D.H. C++ File Processing 10 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 ); }
  • 11. CPSC 231 D.H. C++ File Processing 11 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'; }
  • 12. CPSC 231 D.H. C++ File Processing 12 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
  • 13. CPSC 231 D.H. C++ File Processing 13 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.
  • 14. CPSC 231 D.H. C++ File Processing 14 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.
  • 15. CPSC 231 D.H. C++ File Processing 15 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.
  • 16. CPSC 231 D.H. C++ File Processing 16 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.)
  • 17. CPSC 231 D.H. C++ File Processing 17 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.
  • 18. CPSC 231 D.H. C++ File Processing 18 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
  • 19. CPSC 231 D.H. C++ File Processing 19 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 ); }
  • 20. CPSC 231 D.H. C++ File Processing 20 clientData blankClient = { 0, "", "", 0.0 }; for ( int i = 0; i < 100; i++ ) outCredit.write (reinterpret_cast<const char *>( &blankClient ), sizeof( clientData ) ); return 0; }
  • 21. CPSC 231 D.H. C++ File Processing 21 <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.
  • 22. CPSC 231 D.H. C++ File Processing 22 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 ).
  • 23. CPSC 231 D.H. C++ File Processing 23 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 ); }
  • 24. CPSC 231 D.H. C++ File Processing 24 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;
  • 25. CPSC 231 D.H. C++ File Processing 25 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; }
  • 26. CPSC 231 D.H. C++ File Processing 26 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 ); }
  • 27. CPSC 231 D.H. C++ File Processing 27 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 ) );
  • 28. CPSC 231 D.H. C++ File Processing 28 while ( inCredit && !inCredit.eof() ) { if ( client.accountNumber != 0 ) outputLine( cout, client ); inCredit.read( reinterpret_cast<char *>( &client ), sizeof( clientData ) ); } return 0; }
  • 29. CPSC 231 D.H. C++ File Processing 29 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'; }
  • 30. CPSC 231 D.H. C++ File Processing 30 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.