vsnprintf.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * libcompat - system compatibility library
  3. *
  4. * Copyright © 1995 Ian Jackson <ian@chiark.greenend.org.uk>
  5. * Copyright © 2008-2012 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 <sys/types.h>
  22. #include <unistd.h>
  23. #include <stdarg.h>
  24. #include <stdio.h>
  25. int
  26. vsnprintf(char *buf, size_t maxsize, const char *fmt, va_list args)
  27. {
  28. static FILE *file = NULL;
  29. static pid_t file_pid;
  30. size_t want, nr;
  31. int total;
  32. if (maxsize != 0 && buf == NULL)
  33. return -1;
  34. /* Avoid race conditions from children after a fork(2). */
  35. if (file_pid > 0 && file_pid != getpid()) {
  36. fclose(file);
  37. file = NULL;
  38. }
  39. if (!file) {
  40. file = tmpfile();
  41. if (!file)
  42. return -1;
  43. file_pid = getpid();
  44. } else {
  45. if (fseek(file, 0, 0))
  46. return -1;
  47. if (ftruncate(fileno(file), 0))
  48. return -1;
  49. }
  50. total = vfprintf(file, fmt, args);
  51. if (total < 0)
  52. return -1;
  53. if (maxsize == 0)
  54. return total;
  55. if (total >= (int)maxsize)
  56. want = maxsize - 1;
  57. else
  58. want = total;
  59. if (fflush(file))
  60. return -1;
  61. if (fseek(file, 0, SEEK_SET))
  62. return -1;
  63. nr = fread(buf, 1, want, file);
  64. if (nr != want)
  65. return -1;
  66. buf[want] = '\0';
  67. return total;
  68. }