tags:

views:

60

answers:

2

Comments on my answer here have made me think about how one might implement the same pattern I've been doing with C++ streams. Specifically, I need to be able to have a function which can write to the console, a file, or a string/memory buffer. I don't need most of the formatting features and such that IOStreams provide. Is there some better design which would allow this type of redirection idiomatically that's commonly used in other circles?

for example - for testing I need to be able to write to a string, but for real program use it's always going to be going to a file or the console.

A: 

Well, you may use "CON" filename to write to console as a file, and I believe that's all we can do nice without going over iostream usage complexity.

BarsMonster
That's only going to work on a particular OS, and I can't even imagine which. Reserved filenames went out of style a looong time ago. Macintosh System 4 or 5 did things that way… they changed it as soon as a few more kilobytes were free.
Potatoswatter
There are no pretty solutions here :-) This is for M$ ones. For linux there are similar things.
BarsMonster
Yep `/dev/stdout`… moreover there *is* `fprintf` and the `FILE *stdout, *stdin` objects. But then there are memory buffers, too… I suppose `mmap` is another approach ;v) but that's a bit restrictive.
Potatoswatter
+2  A: 

Totally untested, but you get the idea.

struct stdio_stream {
    enum { invalid_t, file_t, str_t } which;
    union {
        FILE *file_p;
        string *str_p;
    };

    int printf( char *fmt, ... );
    int scanf( char *fmt, ... );

    stdio_stream() : which( invalid_t ), file_p( NULL ) {};

     // etc
};

int stdio_stream::printf( char *fmt, ... ) {
    int ret;
    va_list args;
    va_start( args, fmt );

    if ( which == file_t ) {
        ret = vfprintf( file_p, fmt, args );
    } else if ( which == str_t ) {
        string_p->resize( vsnprintf( NULL, 0, fmt, args )+1, '\0' );
        ret = vsnprintf( &* string_p->begin(), string_p->size(), fmt, args );
    } else throw runtime_error( "uninitialized stream" );

    va_end( args );
    return ret;
}

Personally, I think iostream is just great. If I need to go fast, I'll write a fast parser. printf still has a lot of room for speed improvement… it's a nice middle ground, I suppose, but still just a compromise.

Potatoswatter
I might need an extra `va_start(args); va_end(args);` between the `vsnprintf` calls… not sure.
Potatoswatter
Interesting approach. Note that names ending in `_t` are reserved.
Jon Purdy
@Jon: No they aren't. Not in C++ at least; maybe in C, but this is clearly not C code.
Dennis Zickefoose
@Jon: I don't have a naming convention for discriminated unions. Oh well. Being inside the class prevents name conflicts: the constants must be accessed as `stdio_stream::file_t` etc.
Potatoswatter
@Dennis: They're reserved by POSIX, not the C++ standard proper. @Potatoswatter: Right you are.
Jon Purdy