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
|
Rev | Line | |
---|
[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 |
|
---|
[9320] | 8 | #include <stdarg.h>
|
---|
| 9 | #include <stdio.h>
|
---|
[12460] | 10 | #include "../Alloc/xNewDelete.h"
|
---|
[12438] | 11 | #include "../Alloc/alloc.h"
|
---|
[1] | 12 |
|
---|
[11199] | 13 | char* exprintf(const char* format,...){
|
---|
[1] | 14 |
|
---|
| 15 | /*returned string: */
|
---|
[12460] | 16 | char *buffer = NULL;
|
---|
| 17 | int n,size = 100;
|
---|
[1] | 18 |
|
---|
| 19 | //variable list of arguments
|
---|
[12460] | 20 | va_list args;
|
---|
[1] | 21 |
|
---|
[12460] | 22 | while(true){
|
---|
[1] | 23 |
|
---|
[12460] | 24 | /*allocate buffer for given string size*/
|
---|
[12500] | 25 | buffer=xNew<char>(size);
|
---|
[12460] | 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 |
|
---|
[12500] | 45 | xDelete<char>(buffer);
|
---|
[12460] | 46 | }
|
---|
| 47 |
|
---|
| 48 | return buffer;
|
---|
[1] | 49 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.