vsnprintf.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* Formatted output to strings.
  2. Copyright (C) 2004, 2006-2012 Free Software Foundation, Inc.
  3. Written by Simon Josefsson and Yoann Vandoorselaere <yoann@prelude-ids.org>.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation,
  14. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  15. #ifdef HAVE_CONFIG_H
  16. # include <config.h>
  17. #endif
  18. /* Specification. */
  19. #include <stdio.h>
  20. #include <errno.h>
  21. #include <limits.h>
  22. #include <stdarg.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include "vasnprintf.h"
  26. /* Print formatted output to string STR. Similar to vsprintf, but
  27. additional length SIZE limit how much is written into STR. Returns
  28. string length of formatted string (which may be larger than SIZE).
  29. STR may be NULL, in which case nothing will be written. On error,
  30. return a negative value. */
  31. int
  32. vsnprintf (char *str, size_t size, const char *format, va_list args)
  33. {
  34. char *output;
  35. size_t len;
  36. size_t lenbuf = size;
  37. output = vasnprintf (str, &lenbuf, format, args);
  38. len = lenbuf;
  39. if (!output)
  40. return -1;
  41. if (output != str)
  42. {
  43. if (size)
  44. {
  45. size_t pruned_len = (len < size ? len : size - 1);
  46. memcpy (str, output, pruned_len);
  47. str[pruned_len] = '\0';
  48. }
  49. free (output);
  50. }
  51. if (len > INT_MAX)
  52. {
  53. errno = EOVERFLOW;
  54. return -1;
  55. }
  56. return len;
  57. }