sprintf.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. static const char version[] = "$Id$";
  2. /*
  3. * Copyright 2001-2003, Meiosys (www.meiosys.com). All rights reserved.
  4. *
  5. * See the COPYING file for the terms of usage and distribution.
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <stdarg.h>
  10. #include <string.h>
  11. #include <sd/sprintf.h>
  12. #include <sd/malloc.h>
  13. #include <sd/sd_xplatform.h>
  14. /******************************************************************************/
  15. extern char* sd_sprintf(const char* a_fmt, ...)
  16. {
  17. char* buffer;
  18. va_list args;
  19. va_start(args, a_fmt);
  20. buffer = sd_vsprintf(a_fmt, args);
  21. va_end(args);
  22. return buffer;
  23. }
  24. /******************************************************************************/
  25. extern char* sd_vsprintf(const char* a_fmt, va_list a_args)
  26. {
  27. int size = 10240;
  28. char* buffer = sd_calloc(size, sizeof(char));
  29. va_list ap;
  30. int n;
  31. while (1) {
  32. va_copy(ap, a_args);
  33. n = vsnprintf(buffer, size, a_fmt, ap);
  34. va_end(ap);
  35. /* If that worked, return */
  36. if (n > -1 && n < size)
  37. return buffer;
  38. /* Else try again with more space. */
  39. if (n > -1) /* ISO/IEC 9899:1999 */
  40. size = n + 1;
  41. else /* twice the old size */
  42. size *= 2;
  43. buffer = sd_realloc(buffer, size);
  44. }
  45. }
  46. #if defined(__osf__)
  47. # ifndef snprintf
  48. # include "sprintf.osf.c"
  49. # endif
  50. #endif