snprintf.c 724 B

12345678910111213141516171819202122232425262728
  1. /*
  2. * Throughout the book I use snprintf() because it's safer than sprintf().
  3. * But as of the time of this writing, not all systems provide this
  4. * function. The function below should only be built on those systems
  5. * that do not provide a real snprintf().
  6. * The function below just acts like sprintf(); it is not safe, but it
  7. * tries to detect overflow.
  8. */
  9. #include "unp.h"
  10. #include <stdarg.h> /* ANSI C header file */
  11. int
  12. snprintf(char *buf, size_t size, const char *fmt, ...)
  13. {
  14. int n;
  15. va_list ap;
  16. va_start(ap, fmt);
  17. vsprintf(buf, fmt, ap); /* Sigh, some vsprintf's return ptr, not length */
  18. n = strlen(buf);
  19. va_end(ap);
  20. if (n >= size)
  21. err_quit("snprintf: '%s' overflowed array", fmt);
  22. return(n);
  23. }