vasnprintf.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* vsprintf with automatic memory allocation.
  2. Copyright (C) 2002-2004, 2007-2020 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License along
  12. with this program; if not, see <https://www.gnu.org/licenses/>. */
  13. #ifndef _VASNPRINTF_H
  14. #define _VASNPRINTF_H
  15. /* Get va_list. */
  16. #include <stdarg.h>
  17. /* Get size_t. */
  18. #include <stddef.h>
  19. #ifdef __cplusplus
  20. extern "C" {
  21. #endif
  22. /* Write formatted output to a string dynamically allocated with malloc().
  23. You can pass a preallocated buffer for the result in RESULTBUF and its
  24. size in *LENGTHP; otherwise you pass RESULTBUF = NULL.
  25. If successful, return the address of the string (this may be = RESULTBUF
  26. if no dynamic memory allocation was necessary) and set *LENGTHP to the
  27. number of resulting bytes, excluding the trailing NUL. Upon error, set
  28. errno and return NULL.
  29. When dynamic memory allocation occurs, the preallocated buffer is left
  30. alone (with possibly modified contents). This makes it possible to use
  31. a statically allocated or stack-allocated buffer, like this:
  32. char buf[100];
  33. size_t len = sizeof (buf);
  34. char *output = vasnprintf (buf, &len, format, args);
  35. if (output == NULL)
  36. ... error handling ...;
  37. else
  38. {
  39. ... use the output string ...;
  40. if (output != buf)
  41. free (output);
  42. }
  43. */
  44. #if REPLACE_VASNPRINTF
  45. # define asnprintf rpl_asnprintf
  46. # define vasnprintf rpl_vasnprintf
  47. #endif
  48. extern char * asnprintf (char *restrict resultbuf, size_t *lengthp,
  49. const char *format, ...)
  50. _GL_ATTRIBUTE_FORMAT ((__printf__, 3, 4));
  51. extern char * vasnprintf (char *restrict resultbuf, size_t *lengthp,
  52. const char *format, va_list args)
  53. _GL_ATTRIBUTE_FORMAT ((__printf__, 3, 0));
  54. #ifdef __cplusplus
  55. }
  56. #endif
  57. #endif /* _VASNPRINTF_H */