vsnprintf.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* Formatted output to strings.
  2. Copyright (C) 2004, 2006 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 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 General Public License for more details.
  12. You should have received a copy of the GNU 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 "vsnprintf.h"
  20. #include <errno.h>
  21. #include <limits.h>
  22. #include <stdarg.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include "vasnprintf.h"
  27. /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW. */
  28. #ifndef EOVERFLOW
  29. # define EOVERFLOW E2BIG
  30. #endif
  31. /* Print formatted output to string STR. Similar to vsprintf, but
  32. additional length SIZE limit how much is written into STR. Returns
  33. string length of formatted string (which may be larger than SIZE).
  34. STR may be NULL, in which case nothing will be written. On error,
  35. return a negative value. */
  36. int
  37. vsnprintf (char *str, size_t size, const char *format, va_list args)
  38. {
  39. char *output;
  40. size_t len;
  41. size_t lenbuf = size;
  42. output = vasnprintf (str, &lenbuf, format, args);
  43. len = lenbuf;
  44. if (!output)
  45. return -1;
  46. if (output != str)
  47. {
  48. if (size)
  49. {
  50. size_t pruned_len = (len < size ? len : size - 1);
  51. memcpy (str, output, pruned_len);
  52. str[pruned_len] = '\0';
  53. }
  54. free (output);
  55. }
  56. if (len > INT_MAX)
  57. {
  58. errno = EOVERFLOW;
  59. return -1;
  60. }
  61. return len;
  62. }