Draft 2002-08-14

<fstream>

The <fstream> header declares classes and other types for performing I/O with external files. A file in C++ is a sequences of bytes, which are read as multibyte characters. A narrow (byte) stream or buffer treats the file as a sequence of bytes. A wide stream or buffer reads each multibyte character as a wide character (according to the current locale) or converts wide characters to their multibyte equivalents for writing.

See Chapter 10 for a general discussion of I/O, Chapter 1 for more information about character sets, and the <iostream> section in this chapter for information about the base class templates required by the fstream class templates. Refer to Chapter 9 for information about traits in general and to the <string> section in this chapter for detailed information about the char_traits template. Refer to the <streambuf> section in this chapter for information about the basic_streambuf template.

To open a file for reading, use ifstream; for writing, use ofstream; for reading and writing, use fstream. For wide character I/O, use wifstream, wofstream, or wfstream.

basic_filebuf class template

Class template for file buffers

template <class charT, class traits = char_traits<charT> >
class basic_filebuf : public basic_streambuf<charT,traits>
{
public:
  typedef charT char_type;
  typedef typename traits::int_type int_type;
  typedef typename traits::pos_type pos_type;
  typedef typename traits::off_type off_type;
  typedef traits traits_type;

  basic_filebuf();
  virtual ~basic_filebuf();

  bool is_open() const;
  basic_filebuf<charT,traits>*
    open(const char* filename, ios_base::openmode mode);
  basic_filebuf<charT,traits>* close();
protected:
  virtual streamsize showmanyc();
  virtual int_type underflow();
  virtual int_type uflow();
  virtual int_type pbackfail(int_type c = traits::eof());
  virtual int_type overflow(int_type c = traits::eof());
  virtual basic_streambuf<charT,traits>*
    setbuf(char_type* s, streamsize n);
  virtual pos_type seekoff(off_type off,
    ios_base::seekdir way,
    ios_base::openmode = ios_base::in | ios_base::out);
  virtual pos_type seekpos(pos_type newpos,
    ios_base::openmode which = ios_base::in | ios_base::out);
  virtual int sync();
  virtual void imbue(const locale& loc);
};

The basic_filebuf class template implements a stream buffer that is associated with an external file. The connection to the external file is equivalent to calling C I/O functions (declared in <cstdio>). For example, the open function is equivalent to calling fopen and having the filebuf object store the returned FILE pointer.

The external file is treated as a series of bytes, which might form multibyte characters. When converting the multibyte character sequences to the characters of the file buffer, which are of type charT, the file buffer uses a code conversion facet from the buffer's locale. This codecvt facet is equivalent to a_codecvt, which is declared and initialized as follows:

std::codecvt<charT, char, typename traits::state_type>
  a_codecvt = use_facet<codecvt<charT, char,
                  typename traits::state_type> >(getloc());

Some of the function descriptions in this section refer to a_codecvt, and describe functionality assuming an actual codecvt facet object exists. An implementation does not have to create such an object, provided the resulting behavior is the same.

Remember that codecvt<char, char, mbstate_t> is essentially a no-op, mapping a character to itself, so the codecvt facet is most important when charT is wchar_t.

Following are the member functions of basic_filebuf:

basic_filebuf ()
The constructor initializes the file buffer in a closed state.
virtual ~basic_filebuf ()
The destructor calls close() and finalizes the file buffer.
basic_filebuf<charT, traits>* close ()
The close function closes the file, severing the connection between the external file and the file buffer. If the file is already closed, it returns a null pointer. Otherwise, it calls overflow(EOF) to flush the output buffer. If the buffer most recently called overflow, the external character stream might have an incomplete shift sequence of a multibyte character. The close function therefore calls a_codecvt.unshift() as often as needed to complete the shift sequence, and then calls overflow(EOF) again to flush the buffer. Finally, the external file is closed by calling fclose or its equivalent.
The return value is this for success or NULL for failure.
virtual void imbue (const locale& loc)
The imbue function changes the file buffer's locale, in particular the codecvt facet. It is safe to change the locale when the file is positioned at its beginning, when the character encoding (a_codecvt.encoding()) is not state-dependent, or the old and new locales have the same codecvt facet.
bool is_open () const
The is_open function returns true if the file is open and false if the file is closed.
basic_filebuf<charT, traits>* open (const char* filename, ios_base::openmode mode)
The open function opens the file whose name is given by filename. If a file is already open (is_open() returns true), NULL is returned immediately; otherwise the file buffer is initialized and the named file is opened by calling the equivalent of fopen(filename, modestr). The modestr is determined from the mode (without the ios_base::ate bit), as shown in Table 13-9. No other mode combinations are allowed. If the mode includes ios_base::ate, the opened file is positioned at its end by calling the equivalent of fseek(file, 0, SEEK_END).
If the file is opened successfully, this is returned; otherwise the return value is NULL.
Table 13-9: File open modes
ios_base mode bits fopen equivalent mode string
out "w"
out | app "a"
out | trunc "w"
in "r"
in | out "r+"
in | out | trunc "w+"
binary | out "wb"
binary | out | app "ab"
binary | out | trunc "wb"
binary | in "rb"
binary | in | out "r+b"
binary | in | out | trunc "w+b"
virtual int_type overflow (int_type c = traits::eof())
The overflow function converts its output using a_codecvt.out and writes the converted characters to the external file. The return value is traits::eof() for failure, which also occurs if the file is not open. For success, the return value is traits::not_eof(c).
virtual int_type pbackfail (int_type c = traits::eof())
The pbackfail function tries to push back the character c so it will be the next character read from the input buffer. If a push back position is not available (see <streambuf> for a definition of push back position), the file buffer attempts to make one available, e.g., by moving the file position.
If traits::eq_int_type(c, traits::eof()) is true or if c is the same character as gptr()[-1], the file buffer decrements the gptr() pointer; otherwise if the input array is assignable, c is assigned to gptr()[-1] and gptr() is decremented.
The return value is traits::eof() for failure or c (or traits::not_eof(c) if c is traits::eof()) for success.
virtual pos_type seekoff (off_type off, ios_base::seekdir way, ios_base::openmode = ios_base::in | ios_base::out)
The seekoff function tries to seek to a new position in the file. If the file is not open, the attempt to seek fails. If the character set encoding uses shift states or otherwise does not have a fixed size per character, off must be zero. Otherwise, if the destination is not the current position (off != 0 and way != basic_ios::cur), the output buffer is flushed and unshift sequences are written as needed (a_codecvt.unshift). The new file position is set by calling the equivalent of fseek(file, width * off, origin), where width is a_codecvt.encoding(), and origin is determined as shown in Table 13-10. If width < 0, off must be 0, so the call is fseek(file, 0, origin). The return value is the new file position or -1 for an error or if the new position is unknown. Note that seekoff does not use its final parameter.
Table 13-10: Seek origins
ios_base::seekdir way fseek equivalents
basic_ios::beg SEEK_SET
basic_ios::cur SEEK_CUR
basic_ios::end SEEK_END
virtual pos_type seekpos (pos_type newpos, ios_base::openmode which = ios_base::in | ios_base::out)
The seekpos function attempts to set the file position to newpos, which must be the result of calling seekoff or seekpos on the same file. If which includes the ios_base::in bit, the input sequence is updated; if which includes the ios_base::out bit, the output sequence is updated and any necessary unshift characters are written prior to setting the file position. If neither bit is set in which, it is an error. The return value is -1 for an error or newpos for success.
virtual basic_streambuf<charT, traits>* setbuf (char_type* s, streamsize n)
The setbuf functions sets the buffer. If the function is called as setbuf(0, 0) before any I/O operations are performed on the file, the file is set to unbuffered. The behavior is implementation-defined for any other argument values. The return value is this.
virtual streamsize showmanyc ()
The showmanyc function does the same thing as the base class showmanyc function.
virtual int sync ()
The sync function flushes output to the external file. The behavior for input is implementation-defined.
virtual int_type uflow ()
The uflow function fills the input buffer in the same manner as underflow.
virtual int_type underflow ()
The underflow function fills the input buffer. Multibyte characters are read from the external file and converted to charT characters by calling the equivalent of a_codecvt.in.

See Also

filebuf class, wfilebuf class, basic_streambuf in <streambuf>

basic_fstream class template

Class template for file input and output streams

template <class charT, class traits=char_traits<charT> >
class basic_fstream : public basic_iostream<charT,traits>
{
public:
  typedef charT char_type;
  typedef typename traits::int_type int_type;
  typedef typename traits::pos_type pos_type;
  typedef typename traits::off_type off_type;
  typedef traits traits_type;

  basic_fstream();
  explicit basic_fstream(const char* filename,
    ios_base::openmode mode = ios_base::in|ios_base::out);

  basic_filebuf<charT,traits>* rdbuf() const;
  bool is_open();
  void open(const char* filename,
    ios_base::openmode mode = ios_base::in|ios_base::out);
  void close();
};

The basic_fstream class template supports reading and writing to and from named files, using a basic_filebuf<charT, traits> object. In the following method descriptions, the file buffer object is assumed to be a private data member with the name buf.

basic_fstream ()
The default basic_fstream constructor initializes the base class with basic_iostream(&buf) and initializes buf with its default constructor.
explicit basic_fstream (const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out)
The basic_fstream constructor initializes the base class and buf, then calls open(filename, mode). If open returns NULL, the constructor calls setstate(filebit).
basic_filebuf<charT, traits>* rdbuf () const
The rdbuf function returns &buf.
bool is_open ()
The is_open function returns rdbuf()->is_open().
void open (const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out)
The open function calls rdbuf()->open(filename, mode). If that function returns NULL, open calls setstate(failbit).
void close ()
The close function calls rdbuf()->close(). If that function fails, close calls setstate(failbit).

See Also

basic_filebuf, basic_ios in <ios>, basic_iostream in <istream>

basic_ifstream class template

Class template for file input streams

template <class charT, class traits = char_traits<charT> >
class basic_ifstream : public basic_istream<charT,traits>
{
public:
  typedef charT char_type;
  typedef typename traits::int_type int_type;
  typedef typename traits::pos_type pos_type;
  typedef typename traits::off_type off_type;
  typedef traits traits_type;
  basic_ifstream();
  explicit basic_ifstream(const char* s,
    ios_base::openmode mode = ios_base::in);

  basic_filebuf<charT,traits>* rdbuf() const;
  bool is_open();
  void open(const char* s,
    ios_base::openmode mode = ios_base::in);
  void close();
};

The basic_ifstream class template supports reading from named files, using a basic_filebuf<charT, traits> object. In the following method descriptions, the file buffer object is assumed to be a private data member with the name buf.

basic_ifstream ()
The default basic_ifstream constructor initializes the base class with basic_istream(&buf) and initializes buf with its default constructor.
explicit basic_ifstream (const char* filename, ios_base::openmode mode = ios_base::in)
The basic_ifstream constructor initializes the base class and buf, then calls open(filename, mode). If open returns NULL, the constructor calls setstate(filebit).
basic_filebuf<charT, traits>* rdbuf () const
The rdbuf function returns &buf.
bool is_open ()
The is_open function returns rdbuf()->is_open().
void open (const char* filename, ios_base::openmode mode = ios_base::in)
The open function calls rdbuf()->open(filename, mode). If that function returns NULL, open calls setstate(failbit).
void close ()
The close function calls rdbuf()->close(). If that function fails, close calls setstate(failbit).

See Also

basic_filebuf, basic_ios in <ios>, basic_istream in <istream>

basic_ofstream class template

Class template for file output streams

template <class charT, class traits = char_traits<charT> >
class basic_ofstream : public basic_ostream<charT,traits>
{
public:
  typedef charT char_type;
  typedef typename traits::int_type int_type;
  typedef typename traits::pos_type pos_type;
  typedef typename traits::off_type off_type;
  typedef traits traits_type;

  basic_ofstream();
  explicit basic_ofstream(const char* s,
    ios_base::openmode mode = ios_base::out);
  basic_filebuf<charT,traits>* rdbuf() const;
  bool is_open();
  void open(const char* s,
    ios_base::openmode mode = ios_base::out);
  void close();
};

The basic_ofstream class template supports writing to named files, using a basic_filebuf<charT, traits> object. In the following method descriptions, the file buffer object is assumed to be a private data member with the name buf.

basic_ofstream ()
The default basic_ofstream constructor initializes the base class with basic_ostream(&buf) and initializes buf with its default constructor.
explicit basic_ofstream (const char* filename, ios_base::openmode mode = ios_base::out)
The basic_ofstream constructor initializes the base class and buf, then calls open(filename, mode). If open returns NULL, the constructor calls setstate(filebit).
basic_filebuf<charT, traits>* rdbuf () const
The rdbuf function returns &buf.
bool is_open ()
The is_open function returns rdbuf()->is_open().
void open (const char* filename, ios_base::openmode mode = ios_base::out)
The open function calls rdbuf()->open(filename, mode). If that function returns NULL, open calls setstate(failbit).
void close ()
The close function calls rdbuf()->close(). If that function fails, close calls setstate(failbit).

See Also

basic_filebuf, basic_ios in <ios>, basic_ostream in <ostream>

filebuf class

File buffer

typedef basic_filebuf<char> filebuf;

The filebuf class is a specialization of the basic_filebuf template for char characters.

See Also

basic_filebuf class template, wfilebuf class

fstream class

Input and output file stream

typedef basic_fstream<char> fstream;

The fstream class is a specialization of the basic_fstream template for char characters.

See Also

basic_fstream class template, wfstream class, iostream in <istream>

ifstream class

Input file stream

typedef basic_ifstream<char> ifstream;

The ifstream class is a specialization of the basic_ifstream template for char characters. Example 13-9 shows a simple use of the ifstream and ofstream classes.

Example 13-9: Copying a file using ifstream and ofstream.

#include <fstream>
#include <cstdio>    // for perror()
#include <iostream>  // for cerr

int main(int argc, char** argv)
{
  if (argc != 3) {
    std::cerr << "usage: copy FROM TO\n";
    return 1;
  }

  // Open the input file.
  std::ifstream in(argv[1]);
  if (! in) {
    std::perror(argv[1]);
    return 1;
  }

  // Open the output file.
  std::ofstream out(argv[2]);
  if (! out) {
    std::perror(argv[2]);
    return 1;
  }

  // Copy the input to the output, one character at a time.
  char c;
  while (in.get(c))
    out.put(c);
  out.close();
  // Make sure the output was written.
  if (! out) {
    perror(argv[2]);
    return 1;
  }
}

See Also

basic_ifstream class template, wifstream class, istream in <istream>

ofstream class

Output file stream

typedef basic_ofstream<char> ofstream;

The ofstream class is a specialization of the basic_ofstream template for char characters.

See Also

basic_ofstream class template, wofstream class, ostream in <ostream>

wfilebuf class

Wide character file buffer

typedef basic_filebuf<wchar_t> wfilebuf;

The wfilebuf class is a specialization of the basic_filebuf template for wchar_t characters.

See Also

basic_filebuf class template, filebuf class

wfstream class

Wide character input and output stream

typedef basic_fstream<wchar_t> wfstream;

The wfstream class is a specialization of the basic_fstream template for wchar_t characters.

See Also

basic_fstream class template, fstream class, wiostream in <istream>

wifstream class

Wide character input stream

typedef basic_ifstream<wchar_t> wifstream;

The wifstream class is a specialization of the basic_ifstream template for wchar_t characters.

See Also

basic_ifstream class template, ifstream class, wistream in <istream>

wofstream class

Wide character output stream

typedef basic_ofstream<wchar_t> wofstream;

The wofstream class is a specialization of the basic_ofstream template for wchar_t characters.

See Also

basic_ofstream class template, ofstream class, wostream in <ostream>