vsnprintf.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 <sys/types.h>
  22. #include <sys/stat.h>
  23. #include <stdarg.h>
  24. #include <stdio.h>
  25. #include <unistd.h>
  26. #ifndef HAVE_VSNPRINTF
  27. int
  28. vsnprintf(char *buf, size_t maxsize, const char *fmt, va_list al)
  29. {
  30. static FILE *file = NULL;
  31. struct stat stab;
  32. unsigned long want, nr;
  33. int retval;
  34. if (maxsize == 0)
  35. return -1;
  36. if (!file) {
  37. file = tmpfile();
  38. if (!file)
  39. return -1;
  40. } else {
  41. if (fseek(file, 0, 0))
  42. return -1;
  43. if (ftruncate(fileno(file), 0))
  44. return -1;
  45. }
  46. if (vfprintf(file, fmt, al) == EOF)
  47. return -1;
  48. if (fflush(file))
  49. return -1;
  50. if (fstat(fileno(file), &stab))
  51. return -1;
  52. if (fseek(file, 0, 0))
  53. return -1;
  54. want = stab.st_size;
  55. if (want >= maxsize) {
  56. want = maxsize - 1;
  57. retval = -1;
  58. } else {
  59. retval = want;
  60. }
  61. nr = fread(buf, 1, want - 1, file);
  62. if (nr != want - 1)
  63. return -1;
  64. buf[want] = NULL;
  65. return retval;
  66. }
  67. #endif