Changeset 12460 for issm/trunk-jpl/src


Ignore:
Timestamp:
06/18/12 21:24:07 (13 years ago)
Author:
Mathieu Morlighem
Message:

Better to use vnprintf

File:
1 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/src/c/shared/Exceptions/exprintf.cpp

    r12438 r12460  
    99#include <stdarg.h>
    1010#include <stdio.h>
     11#include "../Alloc/xNewDelete.h"
    1112#include "../Alloc/alloc.h"
    1213
     
    1415
    1516        /*returned string: */
    16         char* string=NULL;
     17        char *buffer = NULL;
     18        int   n,size = 100;
     19        int   string_size;
    1720
    18         /*Assum nobody will print more that 1024 characters!*/
    19         string=(char*)xmalloc(1024*sizeof(char));//assume that nobody will print more than 1024 characters at once.
    20                                                                                                                                                                                                      
    2121        //variable list of arguments
    22         va_list ap;
     22        va_list args;
    2323
    24         //First use vsprintf to get the whole input string.
    25         va_start(ap,format);
    26         vsprintf(string,format,ap); //printf style coding
    27         va_end(ap);
     24        while(true){
    2825
    29         return string;
     26                /*allocate buffer for given string size*/
     27                //buffer=xNew<char>(size);
     28                buffer=(char*)xmalloc(size*sizeof(char));
     29
     30                /* Try to print in the allocated space. */
     31                va_start(args, format);
     32#ifndef WIN32
     33                n=vsnprintf(buffer,size,format,args);
     34#else
     35                n=vsnprintf(buffer,size,format,args);
     36#endif
     37                va_end(args);
     38
     39                /* If that worked, return the string. */
     40                if(n>-1 && n<size) break;
     41
     42                /* Else try again with more space. */
     43                if(n>-1)   /* glibc 2.1 */
     44                 size=n+1; /* precisely what is needed */
     45                else       /* glibc 2.0 */
     46                 size*=2;  /* twice the old size */
     47
     48                xDelete<char>(buffer);
     49        }
     50
     51        return buffer;
    3052}
Note: See TracChangeset for help on using the changeset viewer.