snprintf.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #ifndef HAVE_VPRINTF
  2. #include "choke-me: no vprintf and no snprintf"
  3. choke me.
  4. #endif
  5. #if defined(HAVE_STDARG_H)
  6. # include <stdarg.h>
  7. # ifndef VA_START
  8. # define VA_START(a, f) va_start(a, f)
  9. # define VA_END(a) va_end(a)
  10. # endif /* VA_START */
  11. # define SNV_USING_STDARG_H
  12. #elif defined(HAVE_VARARGS_H)
  13. # include <varargs.h>
  14. # ifndef VA_START
  15. # define VA_START(a, f) va_start(a)
  16. # define VA_END(a) va_end(a)
  17. # endif /* VA_START */
  18. # undef SNV_USING_STDARG_H
  19. #else
  20. # include "must-have-stdarg-or-varargs"
  21. choke me.
  22. #endif
  23. static int
  24. snprintf(char *str, size_t n, char const *fmt, ...)
  25. {
  26. va_list ap;
  27. int rval;
  28. #ifdef VSPRINTF_CHARSTAR
  29. char *rp;
  30. VA_START(ap, fmt);
  31. rp = vsprintf(str, fmt, ap);
  32. VA_END(ap);
  33. rval = strlen(rp);
  34. #else
  35. VA_START(ap, fmt);
  36. rval = vsprintf(str, fmt, ap);
  37. VA_END(ap);
  38. #endif
  39. if (rval > n) {
  40. fprintf(stderr, "snprintf buffer overrun %d > %d\n", rval, (int)n);
  41. abort();
  42. }
  43. return rval;
  44. }
  45. static int
  46. vsnprintf( char *str, size_t n, char const *fmt, va_list ap )
  47. {
  48. #ifdef VSPRINTF_CHARSTAR
  49. return (strlen(vsprintf(str, fmt, ap)));
  50. #else
  51. return (vsprintf(str, fmt, ap));
  52. #endif
  53. }