vsnprintf.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * libcompat - system compatibility library
  3. *
  4. * Copyright © 1995 Ian Jackson <ian@chiark.greenend.org.uk>
  5. *
  6. * This is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as
  8. * published by the Free Software Foundation; either version 2,
  9. * or (at your option) any later version.
  10. *
  11. * This is distributed in the hope that it will be useful, but
  12. * WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public
  17. * License along with dpkg; if not, write to the Free Software
  18. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  19. */
  20. #include <config.h>
  21. #include <stdarg.h>
  22. #include <stdio.h>
  23. #include <unistd.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)
  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 (total >= (int)maxsize)
  47. want = maxsize - 1;
  48. else
  49. want = total;
  50. if (fflush(file))
  51. return -1;
  52. if (fseek(file, 0, SEEK_SET))
  53. return -1;
  54. nr = fread(buf, 1, want, file);
  55. if (nr != want)
  56. return -1;
  57. buf[want] = '\0';
  58. return total;
  59. }
  60. #endif