snprintf.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* Formatted output to strings.
  2. Copyright (C) 2004, 2006-2013 Free Software Foundation, Inc.
  3. Written by Simon Josefsson and Paul Eggert.
  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 3, 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, see <http://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include <stdio.h>
  17. #include <errno.h>
  18. #include <limits.h>
  19. #include <stdarg.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include "vasnprintf.h"
  23. #if defined(_MSC_VER) && _MSC_VER < 1900
  24. /* Print formatted output to string STR. Similar to sprintf, but
  25. additional length SIZE limit how much is written into STR. Returns
  26. string length of formatted string (which may be larger than SIZE).
  27. STR may be NULL, in which case nothing will be written. On error,
  28. return a negative value. */
  29. int
  30. snprintf (char *str, size_t size, const char *format, ...)
  31. {
  32. char *output;
  33. size_t len;
  34. size_t lenbuf = size;
  35. va_list args;
  36. va_start (args, format);
  37. output = vasnprintf (str, &lenbuf, format, args);
  38. len = lenbuf;
  39. va_end (args);
  40. if (!output)
  41. return -1;
  42. if (output != str)
  43. {
  44. if (size)
  45. {
  46. size_t pruned_len = (len < size ? len : size - 1);
  47. memcpy (str, output, pruned_len);
  48. str[pruned_len] = '\0';
  49. }
  50. free (output);
  51. }
  52. if (INT_MAX < len)
  53. {
  54. #if (defined _MSC_VER) && (MSC_VER < 1800)
  55. #else
  56. errno = EOVERFLOW;
  57. #endif
  58. return -1;
  59. }
  60. return len;
  61. }
  62. #endif