Learning Objectives
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 and must be included.
includes and
Creating sequential file
// Fig. 14.4: fig14_04.cpp D&D p.708
// Create a sequential file
#include
#include
#include
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
}
How to open a file in c++
Ofstream outClientFile(“clients.dat”, ios:out)
OR
Ofstream outClientFile;
outClientFile.open(“clients.dat”, ios:out)
Files 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
ios:nocreate – if the file does NOT exists, the open operation fails
ios:noreplace – if the file exists, the open operation fails
How to close a file
The file is closed implicitly when a destructor for the corresponding object is called
OR
by using member function close:
outClientFile.close();
readind an printing a sequential file
// Reading and printing a sequential file
#include
#include
#include
#include
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 opened\n »;
exit( 1 );
}