vasnprintf.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* vsprintf with automatic memory allocation.
  2. Copyright (C) 2002-2004, 2007-2021 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 Lesser General Public License as published by
  5. the Free Software Foundation; either version 2, 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 Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser 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. /* Get _GL_ATTRIBUTE_SPEC_PRINTF_STANDARD. */
  20. #include <stdio.h>
  21. #ifdef __cplusplus
  22. extern "C" {
  23. #endif
  24. /* Write formatted output to a string dynamically allocated with malloc().
  25. You can pass a preallocated buffer for the result in RESULTBUF and its
  26. size in *LENGTHP; otherwise you pass RESULTBUF = NULL.
  27. If successful, return the address of the string (this may be = RESULTBUF
  28. if no dynamic memory allocation was necessary) and set *LENGTHP to the
  29. number of resulting bytes, excluding the trailing NUL. Upon error, set
  30. errno and return NULL.
  31. When dynamic memory allocation occurs, the preallocated buffer is left
  32. alone (with possibly modified contents). This makes it possible to use
  33. a statically allocated or stack-allocated buffer, like this:
  34. char buf[100];
  35. size_t len = sizeof (buf);
  36. char *output = vasnprintf (buf, &len, format, args);
  37. if (output == NULL)
  38. ... error handling ...;
  39. else
  40. {
  41. ... use the output string ...;
  42. if (output != buf)
  43. free (output);
  44. }
  45. */
  46. #if REPLACE_VASNPRINTF
  47. # define asnprintf rpl_asnprintf
  48. # define vasnprintf rpl_vasnprintf
  49. #endif
  50. extern char * asnprintf (char *restrict resultbuf, size_t *lengthp,
  51. const char *format, ...)
  52. _GL_ATTRIBUTE_FORMAT ((_GL_ATTRIBUTE_SPEC_PRINTF_STANDARD, 3, 4));
  53. extern char * vasnprintf (char *restrict resultbuf, size_t *lengthp,
  54. const char *format, va_list args)
  55. _GL_ATTRIBUTE_FORMAT ((_GL_ATTRIBUTE_SPEC_PRINTF_STANDARD, 3, 0));
  56. #ifdef __cplusplus
  57. }
  58. #endif
  59. #endif /* _VASNPRINTF_H */