vsnprintf.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * libcompat - system compatibility library
  3. *
  4. * Copyright © 1995 Ian Jackson <ian@chiark.greenend.org.uk>
  5. * Copyright © 2008, 2009 Guillem Jover <guillem@debian.org>
  6. *
  7. * This is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as
  9. * published by the Free Software Foundation; either version 2,
  10. * or (at your option) any later version.
  11. *
  12. * This is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #include <config.h>
  21. #include <unistd.h>
  22. #include <stdarg.h>
  23. #include <stdio.h>
  24. #ifndef HAVE_VSNPRINTF
  25. int
  26. vsnprintf(char *buf, size_t maxsize, const char *fmt, va_list al)
  27. {
  28. static FILE *file = NULL;
  29. size_t want, nr;
  30. int total;
  31. if (maxsize != 0 && buf == NULL)
  32. return -1;
  33. if (!file) {
  34. file = tmpfile();
  35. if (!file)
  36. return -1;
  37. } else {
  38. if (fseek(file, 0, 0))
  39. return -1;
  40. if (ftruncate(fileno(file), 0))
  41. return -1;
  42. }
  43. total = vfprintf(file, fmt, al);
  44. if (total < 0)
  45. return -1;
  46. if (maxsize == 0)
  47. return total;
  48. if (total >= (int)maxsize)
  49. want = maxsize - 1;
  50. else
  51. want = total;
  52. if (fflush(file))
  53. return -1;
  54. if (fseek(file, 0, SEEK_SET))
  55. return -1;
  56. nr = fread(buf, 1, want, file);
  57. if (nr != want)
  58. return -1;
  59. buf[want] = '\0';
  60. return total;
  61. }
  62. #endif