Chapter 28. Input and Output

Table of Contents

Derived filebufs

Extensions allowing filebufs to be constructed from "C" types like FILE*s and file descriptors.

Derived filebufs

The v2 library included non-standard extensions to construct std::filebufs from C stdio types such as FILE*s and POSIX file descriptors. Today the recommended way to use stdio types with libstdc++ IOStreams is via the stdio_filebuf class (see below), but earlier releases provided slightly different mechanisms.

  • 3.0.x filebufs have another ctor with this signature: basic_filebuf(__c_file_type*, ios_base::openmode, int_type); This comes in very handy in a number of places, such as attaching Unix sockets, pipes, and anything else which uses file descriptors, into the IOStream buffering classes. The three arguments are as follows:

    • __c_file_type* F // the __c_file_type typedef usually boils down to stdio's FILE

    • ios_base::openmode M // same as all the other uses of openmode

    • int_type B // buffer size, defaults to BUFSIZ if not specified

    For those wanting to use file descriptors instead of FILE*'s, I invite you to contemplate the mysteries of C's fdopen().

  • In library snapshot 3.0.95 and later, filebufs bring back an old extension: the fd() member function. The integer returned from this function can be used for whatever file descriptors can be used for on your platform. Naturally, the library cannot track what you do on your own with a file descriptor, so if you perform any I/O directly, don't expect the library to be aware of it.

  • Beginning with 3.1, the extra basic_filebuf constructor and the fd() function were removed from the standard filebuf. Instead, <ext/stdio_filebuf.h> contains a derived class template called __gnu_cxx::stdio_filebuf. This class can be constructed from a C FILE* or a file descriptor, and provides the fd() function.