Subject - Object Oriented Programming With C++ Topic: C++ Stream Classes
Subject - Object Oriented Programming With C++ Topic: C++ Stream Classes
Prepared by-
Vishesh
Vazirani
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.h> includes <ifstream.h> and
<ofstream.h>
2
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 ( !inClientFile ) {
cerr << "File could not be opened\n";
exit( 1 );
}
int account;
char name[ 30 ];
double balance;
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
cout << "Enter account number "
<< "(1 to 100, 0 to end input)\n? ";
clientData client;
cin >> client.accountNumber;
return 0;
}
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 );
}
cout << setiosflags( ios::left ) << setw( 10 ) << "Account"
<< setw( 16 ) << "Last Name" << setw( 11 )
<< "First Name" << resetiosflags( ios::left )
<< setw( 10 ) << "Balance" << endl;
clientData client;
if ( client.accountNumber != 0 )
outputLine( cout, client );
return 0;
}
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';
}
The <istream> function read
inCredit.read (reinterpret_cast<char *>(&client),
sizeof(clientData));