asprintf.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * \file asprintf.c
  3. *
  4. * \brief GIS Library - GRASS implementation of asprintf().
  5. *
  6. * Eric G. Miller - Thu, 2 May 2002 17:51:54 -0700
  7. *
  8. * Rewritten by Glynn Clements, Sat, 6 Feb 2010
  9. * Assumes that vsnprintf() is available
  10. *
  11. * (C) 2001-2008 by the GRASS Development Team
  12. * (C) 2010 by Glynn Clements
  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. #define _GNU_SOURCE /* enable asprintf */
  18. #include <grass/config.h>
  19. #include <stdio.h>
  20. #include <stdarg.h>
  21. #include <string.h>
  22. #include <grass/gis.h>
  23. #ifndef G_asprintf
  24. /**
  25. * \brief Safe replacement for <i>asprintf()</i>.
  26. *
  27. * Allocate a string large enough to hold the new output, including the
  28. * terminating NULL, and returns a pointer to the first parameter. The
  29. * pointer should be passed to <i>G_free()</i> to release the allocated
  30. * storage when it is no longer needed.
  31. *
  32. * \param[out] out
  33. * \param[in] fmt
  34. * \return number of bytes written
  35. */
  36. int G_vasprintf(char **out, const char *fmt, va_list ap)
  37. {
  38. #ifdef HAVE_ASPRINTF
  39. return vasprintf(out, fmt, ap);
  40. #else
  41. size_t size = strlen(fmt) + 50;
  42. char *buf = G_malloc(size);
  43. int count;
  44. for (;;) {
  45. count = vsnprintf(buf, size, fmt, ap);
  46. if (count >= 0 && count < size)
  47. break;
  48. size *= 2;
  49. buf = G_realloc(buf, size);
  50. }
  51. buf = G_realloc(buf, count + 1);
  52. *out = buf;
  53. return count;
  54. #endif /* HAVE_ASPRINTF */
  55. }
  56. int G_asprintf(char **out, const char *fmt, ...)
  57. {
  58. va_list ap;
  59. int count;
  60. va_start(ap, fmt);
  61. count = G_vasprintf(out, fmt, ap);
  62. va_end(ap);
  63. return count;
  64. }
  65. #endif /* G_asprintf */