Last change
on this file since 13622 was 13622, checked in by Mathieu Morlighem, 12 years ago |
CHG: cosmetics, removing all deboule blank lines and indent single white lines correctly
|
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;
|
---|
| 18 | int string_size;
|
---|
[1] | 19 |
|
---|
| 20 | //variable list of arguments
|
---|
[12460] | 21 | va_list args;
|
---|
[1] | 22 |
|
---|
[12460] | 23 | while(true){
|
---|
[1] | 24 |
|
---|
[12460] | 25 | /*allocate buffer for given string size*/
|
---|
[12500] | 26 | buffer=xNew<char>(size);
|
---|
[12460] | 27 |
|
---|
| 28 | /* Try to print in the allocated space. */
|
---|
| 29 | va_start(args, format);
|
---|
| 30 | #ifndef WIN32
|
---|
| 31 | n=vsnprintf(buffer,size,format,args);
|
---|
| 32 | #else
|
---|
| 33 | n=vsnprintf(buffer,size,format,args);
|
---|
| 34 | #endif
|
---|
| 35 | va_end(args);
|
---|
| 36 |
|
---|
| 37 | /* If that worked, return the string. */
|
---|
| 38 | if(n>-1 && n<size) break;
|
---|
| 39 |
|
---|
| 40 | /* Else try again with more space. */
|
---|
| 41 | if(n>-1) /* glibc 2.1 */
|
---|
| 42 | size=n+1; /* precisely what is needed */
|
---|
| 43 | else /* glibc 2.0 */
|
---|
| 44 | size*=2; /* twice the old size */
|
---|
| 45 |
|
---|
[12500] | 46 | xDelete<char>(buffer);
|
---|
[12460] | 47 | }
|
---|
| 48 |
|
---|
| 49 | return buffer;
|
---|
[1] | 50 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.