groff before CVS: release 1.05
[s-roff.git] / lib / tmpfile.c
blobb91893204e9d052d21788ea2a41888a46cdafcc5
1 // -*- C++ -*-
2 /* Copyright (C) 1991 Free Software Foundation, Inc.
3 Written by James Clark (jjc@jclark.uucp)
5 This file is part of groff.
7 groff is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 1, or (at your option) any later
10 version.
12 groff is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License along
18 with groff; see the file LICENSE. If not, write to the Free Software
19 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
21 #include <stdio.h>
22 #include <errno.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #include <osfcn.h>
27 #include "lib.h"
28 #include "errarg.h"
29 #include "error.h"
31 extern "C" {
32 // Sun's stdlib.h fails to declare this.
33 char *mktemp(char *);
36 // If this is set, create temporary files there
37 #define GROFF_TMPDIR_ENVVAR "GROFF_TMPDIR"
38 // otherwise if this is set, create temporary files there
39 #define TMPDIR_ENVVAR "TMPDIR"
40 // otherwise create temporary files here.
41 #define DEFAULT_TMPDIR "/tmp"
42 // Use this as the prefix for temporary filenames.
43 #define TMPFILE_PREFIX "groff"
45 // Open a temporary file with fatal error on failure.
47 FILE *xtmpfile()
49 const char *dir = getenv(GROFF_TMPDIR_ENVVAR);
50 if (!dir) {
51 dir = getenv(TMPDIR_ENVVAR);
52 if (!dir)
53 dir = DEFAULT_TMPDIR;
56 const char *p = strrchr(dir, '/');
57 int needs_slash = (!p || p[1]);
58 char *templ = new char[strlen(dir) + needs_slash
59 + sizeof(TMPFILE_PREFIX) - 1 + 6 + 1];
60 strcpy(templ, dir);
61 if (needs_slash)
62 strcat(templ, "/");
63 strcat(templ, TMPFILE_PREFIX);
64 strcat(templ, "XXXXXX");
66 #ifdef HAVE_MKSTEMP
67 errno = 0;
68 int fd = mkstemp(templ);
69 if (fd < 0)
70 fatal("cannot create temporary file: %1", strerror(errno));
71 errno = 0;
72 FILE *fp = fdopen(fd, "w+");
73 if (!fp)
74 fatal("fdopen: %1", strerror(errno));
75 #else /* not HAVE_MKSTEMP */
76 if (!mktemp(templ) || !templ[0])
77 fatal("cannot create file name for temporary file");
78 errno = 0;
79 FILE *fp = fopen(templ, "w+");
80 if (!fp)
81 fatal("cannot open `%1': %2", templ, strerror(errno));
82 #endif /* not HAVE_MKSTEMP */
83 if (unlink(templ) < 0)
84 error("cannot unlink `%1': %2", templ, strerror(errno));
85 a_delete templ;
86 return fp;
89 #if 0
90 // If you're not running Unix, the following will do:
91 FILE *xtmpfile()
93 FILE *fp = tmpfile();
94 if (!fp)
95 fatal("couldn't create temporary file");
96 return fp;
98 #endif