[ACCEPTED]-Setting the internal buffer used by a standard stream (pubsetbuf)-stream

Accepted answer
Score: 20

After some more research on this problem, and 12 scrutiny of my code, I came across a post suggesting 11 the use of a hand-coded std::streambuf class. The idea 10 behind this code is to create a streambuf that initializes 9 its internals to refer to the given buffer. The 8 code is as follows.

#include <streambuf>

template <typename char_type>
struct ostreambuf : public std::basic_streambuf<char_type, std::char_traits<char_type> >
    ostreambuf(char_type* buffer, std::streamsize bufferLength)
        // set the "put" pointer the start of the buffer and record it's length.
        setp(buffer, buffer + bufferLength);

Now if you look at my original code, you 7 will notice that I didn't really need a 6 stringstream to begin with. All I really needed was 5 a way to write to an external buffer using 4 the IOStream library and std::ostream is a much better type 3 to address this problem. Incidentally, I 2 suspect this is how the array_sink type from Boost.IOStreams is implemented.

Here 1 is the modified code that uses my ostreambuf type.

#include <ostream>
#include "ostreambuf.h"  // file including ostreambuf struct from above.

void FillBuffer(char* buffer, unsigned int size)
    ostreambuf<char> ostreamBuffer(buffer, size);
    std::ostream messageStream(&ostreamBuffer);

    messageStream << "Hello" << std::endl;
    messageStream << "World!" << std::endl;
Score: 5

Looks like a job for the (officially deprecated, but 2 still standard) std::strstream. You could also look at 1 the Boost.IOStreams library, array_sink, in particular.

Score: 1

As the link you posted says: "specific 9 implementations may vary".

Can you not 8 simply return the std::string object and 7 then use std::string::c_str() or std::string::data() at 6 the point the char buffer is required?

Alternatively 5 use sprintf() from the C library, then the 4 whole operation can be completed in the 3 buffer passed. Since that way may result 2 in potential buffer overrun, and you are 1 using Visual C++, you might consider sprintf_s

More Related questions