Chapter 25. Stream Buffers
Prev | Part XI. Input and Output | Next

## Chapter 25. Stream Buffers

## Derived streambuf Classes

Creating your own stream buffers for I/O can be remarkably easy. If you are interested in doing so, we highly recommend two very excellent books: Standard C++ IOStreams and Locales by Langer and Kreft, ISBN 0-201-18395-1, and The C++ Standard Library by Nicolai Josuttis, ISBN 0-201-37926-0. Both are published by Addison-Wesley, who isn't paying us a cent for saying that, honest.

Here is a simple example, io/outbuf1, from the Josuttis text. It transforms everything sent through it to uppercase. This version assumes many things about the nature of the character type being used (for more information, read the books or the newsgroups):

        #include <iostream>
        #include <streambuf>
        #include <locale>
        #include <cstdio>

        class outbuf : public std::streambuf
        {
          protected:
    	/* central output function
    	 * - print characters in uppercase mode
    	 */
    	virtual int_type overflow (int_type c) {
    	    if (c != EOF) {
    		// convert lowercase to uppercase
    		c = std::toupper(static_cast<char>(c),getloc());

    		// and write the character to the standard output
    		if (putchar(c) == EOF) {
    		    return EOF;
    		}
    	    }
    	    return c;
    	}
        };

        int main()
        {
    	// create special output buffer
    	outbuf ob;
    	// initialize output stream with that output buffer
    	std::ostream out(&ob);

    	out << "31 hexadecimal: "
    	    << std::hex << 31 << std::endl;
    	return 0;
        }

Try it yourself! More examples can be found in 3.1.x code, in `include/ext/*_filebuf.h`, and in this article by James Kanze: Filtering Streambufs.

Prev | Up | Next
Chapter 24. Iostream Objects | Home | Buffering