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

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

Final xmalloc

File size: 1.1 KB
Line 
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:
5 * ErrorException(exprintf("%s%i\n","test failed for id:",id));
6 */
7
8
9#include <stdarg.h>
10#include <stdio.h>
11#include "../Alloc/xNewDelete.h"
12#include "../Alloc/alloc.h"
13
14char* exprintf(const char* format,...){
15
16 /*returned string: */
17 char *buffer = NULL;
18 int n,size = 100;
19 int string_size;
20
21 //variable list of arguments
22 va_list args;
23
24 while(true){
25
26 /*allocate buffer for given string size*/
27 buffer=xNew<char>(size);
28
29 /* Try to print in the allocated space. */
30 va_start(args, format);
31#ifndef WIN32
32 n=vsnprintf(buffer,size,format,args);
33#else
34 n=vsnprintf(buffer,size,format,args);
35#endif
36 va_end(args);
37
38 /* If that worked, return the string. */
39 if(n>-1 && n<size) break;
40
41 /* Else try again with more space. */
42 if(n>-1) /* glibc 2.1 */
43 size=n+1; /* precisely what is needed */
44 else /* glibc 2.0 */
45 size*=2; /* twice the old size */
46
47 xDelete<char>(buffer);
48 }
49
50 return buffer;
51}
Note: See TracBrowser for help on using the repository browser.