This item was added on: 2003/03/22
The basics of files are given in the "How do I work with files (C)" section. C++ treats files in the same manner, but with a more object orientated approach. Consider a program that copies one file to another with a command line argument (for consistency with the C section):
#include <iostream>
#include <fstream>
#include <cstdlib>
int main ( int argc, char *argv[] )
{
if ( argc != 3 ) {
std::cerr<<"Usage: %s <readfile1> <writefile2>\n";
std::exit ( EXIT_FAILURE );
}
std::ifstream in ( argv[1] );
if ( !in.is_open() ) {
std::cerr<<"Error opening input file\n";
std::exit ( EXIT_FAILURE );
}
std::ofstream out ( argv[2] );
if ( !out.is_open() ) {
std::cerr<<"Error opening output file\n";
std::exit ( EXIT_FAILURE );
}
char ch;
while ( in.get ( ch ) )
out.put ( ch );
}
A file is opened for input by creating an object of the ifstream
class with the file name as the argument. The same is done for opening a file for output except the class used is ofstream
. In both cases the object should be tested for success.The ofstream
class is declared like so in <fstream>:
template <class Ch, class Tr = char_traits<Ch> >
class basic_ofstream : public basic_ostream<Ch, Tr>
{
public:
basic_ofstream();
explicit basic_ofstream ( const char *p, openmode m = out );
basic_filebuf<Ch, Tr> *rdbuf() const;
bool is_open() const;
void open ( const char *p, openmode m = out );
void close();
};
ifstream
is the same as ofstream
except that it is derived from basic_istream
instead of basic_ostream
and openmode
is defaulted to in instead of out. To protect the user programmer from having to type basic_ofstream<char>
all of the time, typedefs are available:typedef basic_ifstream ifstream;
typedef basic_ofstream ofstream;
typedef basic_fstream fstream;
The openmode
of the constructors and open member functions is defined in the class ios_base
:
app
ate
binary
in
out
trunc
To open a file stream for reading in binary mode, either use ifstream
as binary, or fstream
with ios_base::in
and ios_base::binary
bitwise OR'd together:ifstream in ( filename, ios_base::binary );
or
fstream in ( filename, ios_base::in | ios_base::binary );
It is also possible to open a file stream for both reading and writing by OR'ing together ios_base::in
and ios_base::out
.
As with FILE pointers, fstreams must be closed when you are through with them by way of the member function close. Fortunately, the stream's destructor will do this for you if the end of scope is reached. The close member function isn't needed unless the stream must be closed before the end of the scope is reached or if you feel the need to see an explicit close operation in your source. 
Credit: Prelude