Last change
on this file since 13758 was 13758, checked in by Mathieu Morlighem, 12 years ago |
CHG: some cleanup from cppcheck
|
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 | #include <stdarg.h>
|
---|
9 | #include <stdio.h>
|
---|
10 | #include "../Alloc/xNewDelete.h"
|
---|
11 | #include "../Alloc/alloc.h"
|
---|
12 |
|
---|
13 | char* exprintf(const char* format,...){
|
---|
14 |
|
---|
15 | /*returned string: */
|
---|
16 | char *buffer = NULL;
|
---|
17 | int n,size = 100;
|
---|
18 |
|
---|
19 | //variable list of arguments
|
---|
20 | va_list args;
|
---|
21 |
|
---|
22 | while(true){
|
---|
23 |
|
---|
24 | /*allocate buffer for given string size*/
|
---|
25 | buffer=xNew<char>(size);
|
---|
26 |
|
---|
27 | /* Try to print in the allocated space. */
|
---|
28 | va_start(args, format);
|
---|
29 | #ifndef WIN32
|
---|
30 | n=vsnprintf(buffer,size,format,args);
|
---|
31 | #else
|
---|
32 | n=vsnprintf(buffer,size,format,args);
|
---|
33 | #endif
|
---|
34 | va_end(args);
|
---|
35 |
|
---|
36 | /* If that worked, return the string. */
|
---|
37 | if(n>-1 && n<size) break;
|
---|
38 |
|
---|
39 | /* Else try again with more space. */
|
---|
40 | if(n>-1) /* glibc 2.1 */
|
---|
41 | size=n+1; /* precisely what is needed */
|
---|
42 | else /* glibc 2.0 */
|
---|
43 | size*=2; /* twice the old size */
|
---|
44 |
|
---|
45 | xDelete<char>(buffer);
|
---|
46 | }
|
---|
47 |
|
---|
48 | return buffer;
|
---|
49 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.