source: issm/trunk-jpl/src/c/shared/Exceptions/exprintf.cpp@ 12461

Last change on this file since 12461 was 12461, checked in by Mathieu Morlighem, 13 years ago

minor

File size: 1.2 KB
RevLine 
[1]1/*!\file: exprintf
2 * \brief this is a modification of the sprintf function.
3 * Instead of returning an int, it will return the char* itself.
4 * The advantage is to be able to do things like:
[3570]5 * ErrorException(exprintf("%s%i\n","test failed for id:",id));
[1]6 */
7
8
[9320]9#include <stdarg.h>
10#include <stdio.h>
[12460]11#include "../Alloc/xNewDelete.h"
[12438]12#include "../Alloc/alloc.h"
[1]13
[11199]14char* exprintf(const char* format,...){
[1]15
16 /*returned string: */
[12460]17 char *buffer = NULL;
18 int n,size = 100;
19 int string_size;
[1]20
21 //variable list of arguments
[12460]22 va_list args;
[1]23
[12460]24 while(true){
[1]25
[12460]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
[12461]48 //xDelete<char>(buffer);
49 xfree((void**)&buffer);
[12460]50 }
51
52 return buffer;
[1]53}
Note: See TracBrowser for help on using the repository browser.