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