2 /* Copyright (C) 1989, 1990, 1991, 1992 Free Software Foundation, Inc.
3 Written by James Clark (jjc@jclark.com)
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 2, or (at your option) any later
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
17 You should have received a copy of the GNU General Public License along
18 with groff; see the file COPYING. If not, write to the Free Software
19 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
32 // Sun's stdlib.h fails to declare this.
37 // If this is set, create temporary files there
38 #define GROFF_TMPDIR_ENVVAR "GROFF_TMPDIR"
39 // otherwise if this is set, create temporary files there
40 #define TMPDIR_ENVVAR "TMPDIR"
41 // otherwise create temporary files here.
42 #define DEFAULT_TMPDIR "/tmp"
43 // Use this as the prefix for temporary filenames.
44 #define TMPFILE_PREFIX "groff"
47 * Generate a temporary name template with a postfix
48 * immediately after the TMPFILE_PREFIX.
49 * It uses the groff preferences for a temporary directory.
50 * Note that no file name is either created or opened,
51 * only the *template* is returned.
54 char *xtmptemplate(char *postfix
=0)
56 const char *dir
= getenv(GROFF_TMPDIR_ENVVAR
);
60 postlen
= strlen(postfix
);
63 dir
= getenv(TMPDIR_ENVVAR
);
68 const char *p
= strrchr(dir
, '/');
69 int needs_slash
= (!p
|| p
[1]);
70 char *templ
= new char[strlen(dir
) + needs_slash
71 + sizeof(TMPFILE_PREFIX
) - 1 + 6 + 1 + postlen
];
75 strcat(templ
, TMPFILE_PREFIX
);
77 strcat(templ
, postfix
);
78 strcat(templ
, "XXXXXX");
83 // Open a temporary file and with fatal error on failure.
85 FILE *xtmpfile(char **namep
=0, char *postfix
=0, int do_unlink
=1)
87 char *templ
= xtmptemplate(postfix
);
91 int fd
= mkstemp(templ
);
93 fatal("cannot create temporary file: %1", strerror(errno
));
95 FILE *fp
= fdopen(fd
, "w+");
97 fatal("fdopen: %1", strerror(errno
));
98 #else /* not HAVE_MKSTEMP */
99 if (!mktemp(templ
) || !templ
[0])
100 fatal("cannot create file name for temporary file");
102 FILE *fp
= fopen(templ
, "w+");
104 fatal("cannot open `%1': %2", templ
, strerror(errno
));
105 #endif /* not HAVE_MKSTEMP */
106 if ((do_unlink
) && (unlink(templ
) < 0))
107 error("cannot unlink `%1': %2", templ
, strerror(errno
));
108 if ((namep
!= 0) && ((*namep
) != 0)) {
117 // If you're not running Unix, the following will do:
118 FILE *xtmpfile(char **namep
, char *postfix
=0, int do_unlink
=1)
120 FILE *fp
= tmpfile();
122 fatal("couldn't create temporary file");