Is there a good way to allow a function to write to the console, a file, or a memory buffer without using the IOStream library?
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 f开发者_开发问答ormatting 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.
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.
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.
精彩评论