vsnprintf.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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
  18. * License along with dpkg; if not, write to the Free Software
  19. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. */
  21. #include <config.h>
  22. #include <unistd.h>
  23. #include <stdarg.h>
  24. #include <stdio.h>
  25. #ifndef HAVE_VSNPRINTF
  26. int
  27. vsnprintf(char *buf, size_t maxsize, const char *fmt, va_list al)
  28. {
  29. static FILE *file = NULL;
  30. size_t want, nr;
  31. int total;
  32. if (maxsize != 0 && buf == NULL)
  33. return -1;
  34. if (!file) {
  35. file = tmpfile();
  36. if (!file)
  37. return -1;
  38. } else {
  39. if (fseek(file, 0, 0))
  40. return -1;
  41. if (ftruncate(fileno(file), 0))
  42. return -1;
  43. }
  44. total = vfprintf(file, fmt, al);
  45. if (total < 0)
  46. return -1;
  47. if (maxsize == 0)
  48. return total;
  49. if (total >= (int)maxsize)
  50. want = maxsize - 1;
  51. else
  52. want = total;
  53. if (fflush(file))
  54. return -1;
  55. if (fseek(file, 0, SEEK_SET))
  56. return -1;
  57. nr = fread(buf, 1, want, file);
  58. if (nr != want)
  59. return -1;
  60. buf[want] = '\0';
  61. return total;
  62. }
  63. #endif