snprintf.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*!
  2. * \file lib/gis/snprintf.c
  3. *
  4. * \brief GIS Library - snprintf() clone functions.
  5. *
  6. *
  7. * \todo if needed, implement alternative versions for portability.
  8. * potential code source:
  9. * - http://www.ijs.si/software/snprintf/
  10. * - openssh's snprintf() implementation: bsd-snprintf.c
  11. *
  12. * (C) 2001-2014 by the GRASS Development Team
  13. *
  14. * This program is free software under the GNU General Public License
  15. * (>=v2). Read the file COPYING that comes with GRASS for details.
  16. *
  17. * \author Markus Neteler
  18. *
  19. * \date 2006-2008
  20. */
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <stdarg.h>
  24. #include <unistd.h>
  25. #include <assert.h>
  26. #include <grass/gis.h>
  27. /**
  28. * \brief snprintf() clone.
  29. *
  30. * <b>Note:</b> The use of <i>snprintf()</i>/<i>G_snprintf()</i> is
  31. * discouraged in favour of calculating how long the string will be and
  32. * allocating enough memory!
  33. *
  34. * \param[in] str input string
  35. * \param[in] size length of string
  36. * \param[in] fmt
  37. * \return numer of chars written
  38. */
  39. int G_snprintf(char *str, size_t size, const char *fmt, ...)
  40. {
  41. va_list ap;
  42. int count;
  43. va_start(ap, fmt);
  44. count = vsnprintf(str, size, fmt, ap);
  45. va_end(ap);
  46. /* Windows' vsnprintf() doesn't always NUL-terminate the buffer */
  47. if (count == size)
  48. str[--count] = '\0';
  49. return count;
  50. }