vsnprintf.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This is distributed in the hope that it will be useful,
  13. * but 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. int
  25. vsnprintf(char *buf, size_t maxsize, const char *fmt, va_list args)
  26. {
  27. static FILE *file = NULL;
  28. size_t want, nr;
  29. int total;
  30. if (maxsize != 0 && buf == NULL)
  31. return -1;
  32. if (!file) {
  33. file = tmpfile();
  34. if (!file)
  35. return -1;
  36. } else {
  37. if (fseek(file, 0, 0))
  38. return -1;
  39. if (ftruncate(fileno(file), 0))
  40. return -1;
  41. }
  42. total = vfprintf(file, fmt, args);
  43. if (total < 0)
  44. return -1;
  45. if (maxsize == 0)
  46. return total;
  47. if (total >= (int)maxsize)
  48. want = maxsize - 1;
  49. else
  50. want = total;
  51. if (fflush(file))
  52. return -1;
  53. if (fseek(file, 0, SEEK_SET))
  54. return -1;
  55. nr = fread(buf, 1, want, file);
  56. if (nr != want)
  57. return -1;
  58. buf[want] = '\0';
  59. return total;
  60. }