Reduce code duplication.
[gnulib.git] / lib / fopen-safer.c
1 /* Invoke fopen, but avoid some glitches.
2
3    Copyright (C) 2001, 2004, 2005, 2006 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Written by Paul Eggert.  */
19
20 #include <config.h>
21
22 #include "stdio-safer.h"
23
24 #include <errno.h>
25 #include <unistd.h>
26 #include "unistd-safer.h"
27
28 #ifndef STDERR_FILENO
29 # define STDERR_FILENO 2
30 #endif
31
32 /* Like fopen, but do not return stdin, stdout, or stderr.  */
33
34 FILE *
35 fopen_safer (char const *file, char const *mode)
36 {
37   FILE *fp = fopen (file, mode);
38
39   if (fp)
40     {
41       int fd = fileno (fp);
42
43       if (0 <= fd && fd <= STDERR_FILENO)
44         {
45           int f = dup_safer (fd);
46
47           if (f < 0)
48             {
49               int e = errno;
50               fclose (fp);
51               errno = e;
52               return NULL;
53             }
54
55           if (fclose (fp) != 0
56               || ! (fp = fdopen (f, mode)))
57             {
58               int e = errno;
59               close (f);
60               errno = e;
61               return NULL;
62             }
63         }
64     }
65
66   return fp;
67 }