snprintf.c 1.2 KB

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