choose-temp.c revision 258817
1239310Sdim/* Utility to pick a temporary filename prefix.
2239310Sdim   Copyright (C) 1996, 1997, 1998 Free Software Foundation, Inc.
3239310Sdim
4239310SdimThis file is part of the libiberty library.
5239310SdimLibiberty is free software; you can redistribute it and/or
6239310Sdimmodify it under the terms of the GNU Library General Public
7239310SdimLicense as published by the Free Software Foundation; either
8239310Sdimversion 2 of the License, or (at your option) any later version.
9239310Sdim
10239310SdimLibiberty is distributed in the hope that it will be useful,
11239310Sdimbut WITHOUT ANY WARRANTY; without even the implied warranty of
12239310SdimMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13239310SdimLibrary General Public License for more details.
14249423Sdim
15249423SdimYou should have received a copy of the GNU Library General Public
16249423SdimLicense along with libiberty; see the file COPYING.LIB.  If not,
17249423Sdimwrite to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
18249423SdimBoston, MA 02110-1301, USA.  */
19249423Sdim
20239310Sdim#ifdef HAVE_CONFIG_H
21239310Sdim#include "config.h"
22239310Sdim#endif
23239310Sdim
24249423Sdim#include <stdio.h>	/* May get P_tmpdir.  */
25239310Sdim#ifdef HAVE_STDLIB_H
26239310Sdim#include <stdlib.h>
27239310Sdim#endif
28239310Sdim#ifdef HAVE_STRING_H
29239310Sdim#include <string.h>
30239310Sdim#endif
31239310Sdim
32239310Sdim#include "libiberty.h"
33239310Sdimextern char *choose_tmpdir (void);
34239310Sdim
35239310Sdim/* Name of temporary file.
36239310Sdim   mktemp requires 6 trailing X's.  */
37239310Sdim#define TEMP_FILE "ccXXXXXX"
38239310Sdim#define TEMP_FILE_LEN (sizeof(TEMP_FILE) - 1)
39263508Sdim
40239310Sdim/*
41239310Sdim
42239310Sdim@deftypefn Extension char* choose_temp_base (void)
43239310Sdim
44239310SdimReturn a prefix for temporary file names or @code{NULL} if unable to
45239310Sdimfind one.  The current directory is chosen if all else fails so the
46239310Sdimprogram is exited if a temporary directory can't be found (@code{mktemp}
47239310Sdimfails).  The buffer for the result is obtained with @code{xmalloc}.
48239310Sdim
49239310SdimThis function is provided for backwards compatability only.  Its use is
50239310Sdimnot recommended.
51239310Sdim
52239310Sdim@end deftypefn
53239310Sdim
54239310Sdim*/
55239310Sdim
56239310Sdimchar *
57239310Sdimchoose_temp_base (void)
58239310Sdim{
59239310Sdim  const char *base = choose_tmpdir ();
60239310Sdim  char *temp_filename;
61239310Sdim  int len;
62239310Sdim
63239310Sdim  len = strlen (base);
64239310Sdim  temp_filename = XNEWVEC (char, len + TEMP_FILE_LEN + 1);
65239310Sdim  strcpy (temp_filename, base);
66239310Sdim  strcpy (temp_filename + len, TEMP_FILE);
67239310Sdim
68239310Sdim  if (mktemp (temp_filename) == 0)
69239310Sdim    abort ();
70239310Sdim  return temp_filename;
71239310Sdim}
72239310Sdim