Apache C++ Standard Library Reference Guide

## basic_filebuf

Library: Input/output

    basic_filebuf  basic_streambuf

- Local Index
- Summary
- Synopsis
- Description
- Interface
- Member Types
- Nonmember Types
- Constructors
- Destructors
- Member Functions
- Example
- See Also
- Standards Conformance

### Local Index

#### Members

attach() basic_filebuf() char_type close() detach() fd() | int_type is_open() off_type open() overflow() | pbackfail() pos_type seekoff() seekpos() setbuf() | sync() traits_type underflow() xsputn() ~basic_filebuf()

#### Non-Members

filebuf | wfilebuf |

### Summary

Class that associates the input or output sequence with a file

### Synopsis

    #include <fstream>

    namespace std {
      template<class charT, class traits = char_traits<charT> >
      class basic_filebuf;
    }

### Description

The class template basic_filebuf is derived from basic_streambuf. It associates the input or output sequence with a file. Each object of type basic_filebuf controls two character sequences:

- A character input sequence

- A character output sequence

The restrictions on reading and writing a sequence controlled by an object of class basic_filebuf are the same as for reading and writing with the Standard C library files.

If the file is not open for reading, the input sequence cannot be read. If the file is not open for writing, the output sequence cannot be written. A joint file position is maintained for both the input and output sequences.

A file has byte sequences, so the basic_filebuf class treats a file as the external source (or sink) byte sequence. In order to provide the contents of a file as wide character sequences, a wide-oriented file buffer called wfilebuf converts wide character sequences to multibyte character sequences (and vice versa) according to the current locale being used in the stream buffer.

### Interface

    namespace std {

      template<class charT, class traits = char_traits<charT> >
      class basic_filebuf : public basic_streambuf<charT, traits>
      {
       public:

        typedef traits                       traits_type;
        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;

        basic_filebuf();

        // extensions:
        basic_filebuf(int, char_type*, streamsize);
        basic_filebuf(FILE*, char_type*, streamsize);

        virtual ~basic_filebuf();

        bool is_open() const;

        // extensions:
        basic_filebuf<charT, traits>* open(const char*,
                                           ios_base::openmode,
                                           long = 0666);
        basic_filebuf<charT, traits>* open(int, char_type* = 0,
                                           streamsize = /* default size */);
        basic_filebuf<charT, traits>* open(FILE *, char_type*,
                                           streamsize);
        basic_filebuf<charT, traits>* attach(int);
        int detach();

        int fd() const;

        basic_filebuf<charT, traits>* close();

       protected:

        virtual int      showmanyc();
        virtual int_type underflow();
        virtual int_type overflow(int_type = traits::eof());
        virtual int_type pbackfail(int_type = traits::eof());

        virtual basic_streambuf<charT,traits>*
        setbuf(char_type*,streamsize);

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

        virtual pos_type seekpos(pos_type,
                                 ios_base::openmode =
                                 ios_base::in | ios_base::out);
        virtual int sync();
        virtual streamsize xsputn(const char_type*,
                                  streamsize);

    };

### Member Types

    char_type

The type `char_type` is a synonym for the template parameter `charT`.

    int_type

The type `int_type` is a synonym of type `traits::int_type`.

    off_type

The type `off_type` is a synonym of type `traits::off_type`.

    pos_type

The type `pos_type` is a synonym of type `traits::pos_type`.

    traits_type

The type `traits_type` is a synonym for the template parameter `traits`.

### Nonmember Types

    filebuf

The type `filebuf` is a specialization of class template basic_filebuf on type `char`:

`typedef basic_filebuf<char> filebuf;`

    wfilebuf

The type `wfilebuf` is a specialization of class template basic_filebuf on type `wchar_t`:

`typedef basic_filebuf<wchar_t> wfilebuf;`

### Constructors

    basic_filebuf();

Constructs an object of class basic_filebuf, initializing the base class with `basic_streambuf<charT,traits>()`.

    basic_filebuf(int fd, char_type *buf = 0,
                  streamsize n = /* default size */);

Constructs an object of class basic_filebuf, initializing the base class with `basic_streambuf<charT,traits>()`. It then calls `open(fd, buf, n)`.

> NOTE -- This function is not part of the C++ Standard, but is included here as an extension to manipulate pipes, sockets, or other UNIX devices that can be accessed through file descriptors. See Appendix B for a complete list of extensions of this implementation.

    basic_filebuf(FILE *fp, char_type *buf = 0,
                  streamsize n = /* default size */);

Constructs an object of class basic_filebuf, initializing the base class with `basic_streambuf<charT,traits>()`. It then calls `open(fp, buf, n)`.

> NOTE -- This function is not part of the C++ Standard, but is included here as an extension. See Appendix B for a complete list of extensions of this implementation.

### Destructors

    virtual ~basic_filebuf();

Calls `close()` and destroys the object.

### Member Functions

    basic_filebuf<charT, traits>*
    attach(int fd);

Attaches the object to the open file descriptor `fd`. Unless `detach()` is called, the file descriptor will be closed during the next call to `close()` or at the time the object is destroyed. Returns `this` on success; otherwise returns `0` (for example, when `is_open()` returns `true` prior to the call).

> NOTE -- This function is not part of the C++ Standard, but is provided as an extension of this implementation for compatibility with Classic Iostreams. See Appendix B for a complete list of extensions of this implementation.

    int
    fd() const;

If `is_open()` returns `true`, returns the associated file descriptor, otherwise -1.

> NOTE -- This function is not part of the C++ Standard, but is provided as an extension of this implementation for compatibility with Classic Iostreams. See Appendix B for a complete list of extensions of this implementation.

    basic_filebuf<charT,traits>*
    close();

If `is_open() == false`, returns a null pointer. Otherwise, if a `put` area exists, calls `overflow(traits_type::eof())` to flush the contents of the buffer. If `overflow()` is the last virtual member function called on an object, among the functions `underflow()`, `overflow()`, `seekoff()`, and `seekpos()`, the `close()` function calls:

       use_facet<codecvt  <char_type, char,
                           typename traits_type::state_type>
                             >(getloc()).unshift

The call is made one or more times to determine a termination sequence. The `close()` function then inserts the characters of the termination sequence, calls `overflow(traits_type::eof())` again, and closes the file, just like a call to `std::fclose`.

    int
    detach();

Flushes any pending output to the file associated with the object and, if the operation succeeds, disassociates the object from the underlying file descriptor or `FILE*` without closing the latter. Returns `fd()` on success. Returns `-1` on failure (for example, when the object was unable to flush the pending output).

> NOTE -- This function is not part of the C++ Standard, but is provided as an extension of this implementation for compatibility with Classic Iostreams. See Appendix B for a complete list of extensions of this implementation.

    bool
    is_open() const;

Returns `true` if the associated file is open.

    basic_filebuf<charT,traits>*
    open(const char* fname, ios_base::openmode mode,
         long protection = 0666);

If `is_open() == true`, returns a null pointer. Otherwise, if `(fname != 0)` evaluates to `true`, opens the file whose name is stored in the NUL-terminated byte string `fname`.

Otherwise, if `(fname == 0)` evaluates to `true`, attempts to create a temporary file with a unique name (obtained, for example, by a call to `std::tmpnam()` or a similar function. ) The temporary file will be deleted on the first call to `close()` on the object or when the last file descriptor referring to the file is closed, whichever occurs last. Note that the file will be deleted by the operating system even if the program exits abnormally.

> NOTE -- The behavior of the function when `(fname == 0)` evaluates to true is not required by the C++ Standard, but is provided as an extension of this implementation. See Appendix B for a complete list of extensions of this implementation.

The file open modes are given by their C-equivalent descriptions (see the C function `fopen()`). They are:

    in                      "r"
    in|binary               "rb"
    out                     "w"
    out|app                 "a"
    out|binary              "wb"
    out|binary|app          "ab"
    out|in                  "r+"
    out|in|app              "a+"
    out|in|binary           "r+b"
    out|in|binary|app       "a+b"
    trunc|out               "w"
    trunc|out|binary        "wb"
    trunc|out|in            "w+"
    trunc|out|in|binary     "w+b"

If `open()` succeeds and `(mode & ios_base::ate) != 0`, it positions the file to the end, like a call to `std::fseek(file, 0, SEEK_END))`. If the `open()` function fails, it returns a null pointer.

The third argument, `protection`, is used as the file permission. The `protection` argument determines the read/write/execute file permissions under UNIX. It is more limited under DOS, since files are always readable and do not have special execute permission.

> NOTE -- The protection argument does not appear in the C++ Standard, but is included here as an extension. See Appendix B for a complete list of extensions of this implementation.

    basic_filebuf<charT,traits>*
    open(int fd, char_type *buf = 0,
         streamsize n = /* default size */);

Attaches the previously opened file, which is identified by its file descriptor, `fd`, to the basic_filebuf object.

> NOTE -- This function is not part of the C++ Standard, but is included here as an extension in order to manipulate pipes, sockets, or other UNIX devices that can be accessed through file descriptors. See Appendix B for a complete list of extensions of this implementation.

    basic_filebuf<charT,traits>*
    open(FILE *fp, char_type *buf = 0,
         streamsize n = /* default size */);

Returns `open(fileno (fp), buf, n)`, where `fileno` is a UNIX98 function declared in `<cstdio>`.

> NOTE -- This function is not part of the C++ Standard, but is provided as a convenience extension. See Appendix B for a complete list of extensions of this implementation.

    int_type
    overflow(int_type c = traits_type::eof());

If the output sequence has a `put` position available, and `c` is not`traits_type::eof()`, then writes `c` into it. If there is no position available, the function outputs the contents of the buffer to the associated file and writes `c` at the new current `put` position. If the operation fails, the function returns `traits_type``::eof()`; otherwise, it returns `traits_type``::not_eof(c)`. In a wide character file buffer, `overflow()` may convert the internal wide characters to their external multibyte representation by using the `locale::codecvt` facet located in the locale object imbued in the stream buffer.

    int_type
    pbackfail(int_type c = traits_type::eof());

Puts back the character designated by `c` into the input sequence. If `traits_type::eq_int_type(c,traits_type::eof())` returns `true`, moves the input sequence one position backward. If the operation fails, the function returns `traits_type::eof()`. Otherwise, it returns `traits::not_eof(c)`.

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

If the open mode is `in|out`, may alter the stream position of the input and the output sequence as follows:

- If the open mode is `in`, may alter the stream position of only the input sequence

- If the open mode is `out`, may alter the stream position of only the output sequence

The new position is calculated by combining the two parameters `off` (displacement) and `way` (reference point). Note the following cases:

- If the current position of the sequence is invalid before repositioning, the operation fails and the return value is:

`pos_type(off_type(-1))`

- If `way != basic_ios::cur` or `off != 0`, and the last operation was output, the function updates the output sequence and writes any unshift sequence. It then repositions the file, like a call to `std::fseek(file, 0, whence)`, and returns the current new position.

File buffers that use the `locale::codecvt` facet, and perform state dependent conversion, support seeking only to the beginning of the file, to the current position, or to a position previously obtained by a call to one of the iostreams seeking functions.

    pos_type
    seekpos(pos_type sp,ios_base::openmode
              which = ios_base::in | ios_base::out);

If the open mode is `in|out`, alters the stream position of both the input and the output sequence. If the open mode is `in`, alters the stream position of only the input sequence, and if it is `out`, alters the stream position of only the output sequence. If the current position of the sequence is invalid before repositioning, the operation fails and the return value is `pos_type(off_type(-1))`. Otherwise, the function returns the current new position. File buffers using `locale::codecvt` facet performing state dependent conversion only support seeking to the beginning of the file, to the current position, or to a position previously obtained by a call to one of the iostreams seeking functions.

    basic_filebuf<charT,traits>*
    setbuf(char_type *s, streamsize n);

The function first flushes the contents of the `put` area into the associated file, if necessary. Then:

- If both `s` and `n` are `0`, the function places the object in an unbuffered mode, that is, `pbase()` and `pptr()` always return null and output to the file appears immediately.

- If `s` is null and `n` is nonzero, the function allocates an internal character buffer of size `n` and takes ownership of the buffer.

- If `s` is non-null and `n` is nonzero, the function uses the provided buffer in place of its internal buffer. The caller is responsible for deallocating the provided buffer, or the function fails.

The function returns `this` on success and `0` on failure.

    int
    sync();

Synchronizes the contents of the external file, with its image maintained in memory by the file buffer. This is useful, for instance, when two threads of execution simultaneously manipulate the same file. If the function fails, it returns `-1`; otherwise, it returns `0`.

    int_type
    underflow();

If the input sequence has a read position available, returns the contents of this position. Otherwise fills up the buffer by reading characters from the associated file, and if it succeeds, returns the contents of the new current position. The function returns `traits_type::eof()` to indicate failure. In wide characters file buffer, `underflow` may convert the external multibytes characters to their wide character representation by using the `locale::codecvt` facet located in the locale object imbued in the stream buffer.

    streamsize
    xsputn(const char_type* s, streamsize n);

Writes up to `n` characters to the output sequence. The characters written are obtained from successive elements of the array whose first element is designated by `s`. The function returns the number of characters written.

### Example

    //
    //  filebuf.cpp
    //

    #include <iostream>   // for cout, endl
    #include <fstream>    // for ifstream, ofstream

    #include <stdio.h>    // for tmpnam, remove

    int main ( )
    {
        char filebuf [L_tmpnam];

        // create a temporary filename
        const char *fname = tmpnam (filebuf);

        if (!fname)
            return 1;

        // create a read/write file-stream object on tiny char
        // and attach it to the file "filebuf.out"
        std::ofstream out (fname, std::ios::in | std::ios::out |
                                  std::ios::trunc);

        // tie the istream object to the ofstream object
        std::istream in (out.rdbuf ());

        // output to out
        out << "Il errait comme un ame en peine";

        // seek to the beginning of the file
        in.seekg (0);

        // output in to the standard output
        std::cout << in.rdbuf () << std::endl;

        // close the file
        out.close ();

        // open the existing temporary file and truncate it
        out.open (fname, std::ios::in | std::ios::out |
                         std::ios::trunc);

        // set the buffer size
        // buffer will be allocated internally
        // and deallocated in dtor
        out.rdbuf ()->pubsetbuf (0, 4096);

        // open this source code file
        std::ifstream ins (__FILE__);

        // output it to temporary file
        out << ins.rdbuf ();

        // seek to the beginning of the file
        out.seekp (0);

        // output the all file
        std::cout << out.rdbuf ();

        // remove temporary file
        remove (fname);

        return 0;
    }

    Program Output:
    Il errait comme un ame en peine
    //
    //  filebuf.cpp
    //

    #include <iostream>   // for cout, endl
    #include <fstream>    // for ifstream, ofstream

    #include <stdio.h>    // for tmpnam, remove

    int main ( )
    {
        char filebuf [L_tmpnam];

        // create a temporary filename
        const char *fname = tmpnam (filebuf);

        if (!fname)
            return 1;

        // create a read/write file-stream object on tiny char
        // and attach it to the file "filebuf.out"
        std::ofstream out (fname, std::ios::in | std::ios::out |
                                  std::ios::trunc);

        // tie the istream object to the ofstream object
        std::istream in (out.rdbuf ());

        // output to out
        out << "Il errait comme un ame en peine";

        // seek to the beginning of the file
        in.seekg (0);

        // output in to the standard output
        std::cout << in.rdbuf () << std::endl;

        // close the file
        out.close ();

        // open the existing temporary file and truncate it
        out.open (fname, std::ios::in | std::ios::out |
                         std::ios::trunc);

        // set the buffer size
        // buffer will be allocated internally
        // and deallocated in dtor
        out.rdbuf ()->pubsetbuf (0, 4096);

        // open this source code file
        std::ifstream ins (__FILE__);

        // output it to temporary file
        out << ins.rdbuf ();

        // seek to the beginning of the file
        out.seekp (0);

        // output the all file
        std::cout << out.rdbuf ();

        // remove temporary file
        remove (fname);

        return 0;
    }

### See Also

char_traits, ios_base, basic_ios, basic_streambuf, basic_ifstream, basic_ofstream, basic_fstream

### Standards Conformance

ISO/IEC 14882:1998 -- International Standard for Information Systems --Programming Language C++, Section 27.8.1.1