fopen-safer.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* Invoke fopen, but avoid some glitches.
  2. Copyright (C) 2001, 2004-2006, 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. /* Written by Paul Eggert. */
  14. #include <config.h>
  15. #include "stdio-safer.h"
  16. #include <errno.h>
  17. #include <unistd.h>
  18. #include "unistd-safer.h"
  19. /* Like fopen, but do not return stdin, stdout, or stderr. */
  20. FILE *
  21. fopen_safer (char const *file, char const *mode)
  22. {
  23. FILE *fp = fopen (file, mode);
  24. if (fp)
  25. {
  26. int fd = fileno (fp);
  27. if (0 <= fd && fd <= STDERR_FILENO)
  28. {
  29. int f = dup_safer (fd);
  30. if (f < 0)
  31. {
  32. int e = errno;
  33. fclose (fp);
  34. errno = e;
  35. return NULL;
  36. }
  37. if (fclose (fp) != 0
  38. || ! (fp = fdopen (f, mode)))
  39. {
  40. int e = errno;
  41. close (f);
  42. errno = e;
  43. return NULL;
  44. }
  45. }
  46. }
  47. return fp;
  48. }