DekGenius.com
Team LiB   Previous Section   Next Section

13.24 <fstream>

The <fstream> header declares classes and other types for performing I/O with external files. A file in C++ is a sequence of bytes. A narrow (byte) stream or buffer simply reads or writes those bytes. A wide stream or buffer reads multibyte characters and converts them to wide characters (according to the stream's locale) or converts wide characters to their multibyte equivalents for writing.

See Chapter 9 for a general discussion of I/O and related topics (stream buffers, locales, and facets), 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 8 for information about traits in general and to the <string> section in this chapter for detailed information about the char_traits class template. Refer to the <streambuf> section in this chapter for information about the basic_streambuf class 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>* 
    open(const char* filename, ios_base::open_mode 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>) but may or may not actually call the C functions. 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 characters in 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 that an actual codecvt facet object exists. An implementation does not have to create a codecvt facet object as long as the file stream acts as though it did create and use an explicit codecvt facet. (See <locale> for more information about codecvt.)

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.

See <streambuf> for a description of the required behavior of a stream buffer, especially for the virtual functions that basic_filebuf overrides.

The following are the member functions of basic_filebuf:

basic_filebuf( )

Initializes the file buffer in a closed state.

virtual ~basic_filebuf( )

Calls close( ) and finalizes the file buffer.

basic_filebuf<charT, traits>* close( )

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 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 a null pointer for failure.

virtual void imbue(const locale& loc)

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

Returns true if the file is open or false if the file is closed.

basic_filebuf<charT, traits>*
open(const char* filename, ios_base::openmode mode)
basic_filebuf<charT, traits>*
open(const char* filename, ios_base::open_mode mode)

Opens the file filename. If the file is already open (is_open( ) returns true), a null pointer 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).

The second form is deprecated. It has the same functionality as the first form. See ios_base::openmode in <ios> for details.

If the file is opened successfully, this is returned; otherwise, the return value is a null pointer.

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( ))

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( ))

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 c is traits::eof( ) or 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 traits::not_eof(c) for success.

virtual pos_type seekoff(off_type off, ios_base::seekdir way, ios_base::openmode = ios_base::in | ios_base::out)

Tries to seek to a new position in the file as an offset from a defined position. 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 0. Otherwise, if the destination is not the current position (off != 0 or 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), in which 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 options

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)

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, an error results. The return value is -1 for an error or newpos for success.

figs/acorn.gifvirtual basic_streambuf<charT, traits>* setbuf(char_type* s, streamsize n)

Sets the buffer. If you call setbuf(0, 0) before any I/O operations are performed on a 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( )

Returns an estimate of the number of characters immediately available for input.In other words, it does the same thing as the base class showmanyc function.

figs/acorn.gifvirtual int sync( )

Flushes output to the external file. The behavior for input is implementation-defined.

virtual int_type uflow( )

Fills the input buffer in the same manner as underflow.

virtual int_type underflow( )

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. (See <istream> for a description of the base-class template, basic_iostream.) In the following member function descriptions, the file buffer object is assumed to be a private data member with the name buf.

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)

Initializes the base class and buf, then calls open(filename, mode). If open returns a null pointer, the constructor calls setstate(failbit).

basic_filebuf<charT, traits>* rdbuf( ) const

Returns &buf.

bool is_open( )

Returns rdbuf( )->is_open( ).

void open(const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out)

Calls rdbuf( )->open(filename, mode). If that function returns a null pointer, open calls setstate(failbit).

void close( )

Calls rdbuf( )->close( ). If that function fails, close calls setstate(failbit).

See Also

basic_filebuf class template, 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 open(const char* s, ios_base::open_mode mode);
  void close(  );
};

The basic_ifstream class template supports reading from named files using a basic_filebuf<charT, traits> object. (See <istream> for a description of the base-class template, basic_istream.) In the following member function descriptions, the file buffer object is assumed to be a private data member with the name buf:

basic_ifstream( )

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)

Initializes the base class and buf, then calls open(filename, mode). If open returns a null pointer, the constructor calls setstate(failbit).

basic_filebuf<charT, traits>* rdbuf( ) const

Returns &buf.

bool is_open( )

Returns rdbuf( )->is_open( ).

void open(const char* filename, ios_base::openmode mode = ios_base::in)
void open(const char* filename,ios_base::open_mode mode)

Calls rdbuf( )->open(filename, mode). If that function returns a null pointer, open calls setstate(failbit). The second form is deprecated. It has the same functionality as the first form. See ios_base::openmode in <ios> for details.

void close( )

Calls rdbuf( )->close( ). If that function fails, close calls setstate(failbit).

See Also

basic_filebuf class template, 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 open(const char* s, ios_base::open_mode mode);
  void close(  );
};

The basic_ofstream class template supports writing to named files using a basic_filebuf<charT, traits> object. (See <ostream> for a description of the base-class template, basic_ostream.) In the following member function descriptions, the file buffer object is assumed to be a private data member with the name buf:

basic_ofstream( )

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)

Initializes the base class and buf, then calls open(filename, mode). If open returns a null pointer, the constructor calls setstate(failbit).

basic_filebuf<charT, traits>* rdbuf( ) const

Returns &buf.

bool is_open( )

Returns rdbuf( )->is_open( ).

void open(const char* filename, ios_base::openmode mode = ios_base::out)
void open(const char* filename,ios_base::open_mode mode)

Calls rdbuf( )->open(filename, mode). If that function returns a null pointer, open calls setstate(failbit). The second form is deprecated. It has the same functionality as the first form. See ios_base::openmode in <ios> for details.

void close( )

Calls rdbuf( )->close( ). If that function fails, close calls setstate(failbit).

See Also

basic_filebuf class template, 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

Example 13-9. Copying a file using ifstream and ofstream
#include <cstdlib>
#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 EXIT_FAILURE;
  }
   
  // Open the input file.
  std::ifstream in(argv[1]);
  if (! in) {
    std::perror(argv[1]);
    return EXIT_FAILURE;
  }
   
  // Open the output file.
  std::ofstream out(argv[2]);
  if (! out) {
    std::perror(argv[2]);
    return EXIT_FAILURE;
  }
   
  // 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) {
    std::perror(argv[2]);
    return EXIT_FAILURE;
  }
}

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>

    Team LiB   Previous Section   Next Section