xprintf.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* printf wrappers that fail immediately for non-file-related errors
  2. Copyright (C) 2007, 2009-2013 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. #include <config.h>
  14. #include "xprintf.h"
  15. #include <errno.h>
  16. #include "error.h"
  17. #include "exitfail.h"
  18. #include "gettext.h"
  19. /* written by Jim Meyering */
  20. /* Just like printf, but call error if it fails without setting the
  21. stream's error indicator. */
  22. int
  23. xprintf (char const *restrict format, ...)
  24. {
  25. va_list args;
  26. int retval;
  27. va_start (args, format);
  28. retval = xvprintf (format, args);
  29. va_end (args);
  30. return retval;
  31. }
  32. /* Just like vprintf, but call error if it fails without setting the
  33. stream's error indicator. */
  34. int
  35. xvprintf (char const *restrict format, va_list args)
  36. {
  37. int retval = vprintf (format, args);
  38. if (retval < 0 && ! ferror (stdout))
  39. error (exit_failure, errno, gettext ("cannot perform formatted output"));
  40. return retval;
  41. }
  42. /* Just like fprintf, but call error if it fails without setting the
  43. stream's error indicator. */
  44. int
  45. xfprintf (FILE *restrict stream, char const *restrict format, ...)
  46. {
  47. va_list args;
  48. int retval;
  49. va_start (args, format);
  50. retval = xvfprintf (stream, format, args);
  51. va_end (args);
  52. return retval;
  53. }
  54. /* Just like vfprintf, but call error if it fails without setting the
  55. stream's error indicator. */
  56. int
  57. xvfprintf (FILE *restrict stream, char const *restrict format, va_list args)
  58. {
  59. int retval = vfprintf (stream, format, args);
  60. if (retval < 0 && ! ferror (stream))
  61. error (exit_failure, errno, gettext ("cannot perform formatted output"));
  62. return retval;
  63. }