opendirat: don’t depend on openat-safer
[gnulib.git] / lib / tmpfile-safer.c
blobbe990f6eb6790e28d23ee174c8c302dc1f3b65b8
1 /* Invoke tmpfile, but avoid some glitches.
2 Copyright (C) 2006, 2009-2024 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Written by Eric Blake, based on ideas from Paul Eggert. */
19 #include <config.h>
21 #include "stdio-safer.h"
23 #include <errno.h>
24 #include <unistd.h>
25 #include "unistd-safer.h"
27 #include "binary-io.h"
29 /* Like tmpfile, but do not return stdin, stdout, or stderr.
31 Remember that tmpfile can leave files behind if your program calls _exit,
32 so this function should not be mixed with the close_stdout module. */
34 FILE *
35 tmpfile_safer (void)
37 FILE *fp = tmpfile ();
39 if (fp)
41 int fd = fileno (fp);
43 if (0 <= fd && fd <= STDERR_FILENO)
45 int f = dup_safer (fd);
47 if (f < 0)
49 int e = errno;
50 fclose (fp);
51 errno = e;
52 return NULL;
55 /* Keep the temporary file in binary mode, on platforms
56 where that matters. */
57 if (fclose (fp) != 0
58 || ! (fp = fdopen (f, O_BINARY ? "wb+" : "w+")))
60 int e = errno;
61 close (f);
62 errno = e;
63 return NULL;
68 return fp;