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

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

Better to use vnprintf

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 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;
52}
Note: See TracBrowser for help on using the repository browser.