makestring.cpp

Go to the documentation of this file.
00001 #include <stdio.h>
00002 #include <stdlib.h>
00003 #include <stdarg.h>
00004 #include <string.h>
00005 #include <string>
00006 
00007 std::string make_string( const char* fmt, ... ) {
00008     va_list ap;
00009     int lMessage = 256;
00010     char *message = ( char * ) malloc( lMessage * sizeof( char ) );
00011     *message = 0;
00012     int nChars = strlen( message );
00013     while ( 1 ) {
00014         /* Try to print in the allocated space. */
00015         va_start( ap, fmt );
00016 #ifdef _GNU_SOURCE
00017 
00018         int n = vsnprintf ( message + nChars, lMessage - nChars - 1, fmt, ap );
00019 #else
00020 
00021         int n = vsprintf ( message + nChars, fmt, ap );
00022 #endif
00023 
00024         va_end( ap );
00025         /* If that worked, return else alloc more memory */
00026         if ( n > -1 && n < lMessage - nChars - 1 ) {
00027             std::string msg( message );
00028             free( message );
00029             return msg;
00030         } else {
00031             lMessage *= 2;
00032             message = ( char * ) realloc( message, lMessage * sizeof( char ) );
00033         }
00034     }
00035 }

Generated on Wed Jul 9 16:34:39 2008 for PCSIM by  doxygen 1.5.5