xref: /netbsd-src/external/gpl3/gdb.old/dist/libiberty/tmpnam.c (revision bb16d22702ff57c46e117881dd16b08ca16721cc)
1*bb16d227Schristos /*
2*bb16d227Schristos 
3*bb16d227Schristos @deftypefn Supplemental char* tmpnam (char *@var{s})
4*bb16d227Schristos 
5*bb16d227Schristos This function attempts to create a name for a temporary file, which
6*bb16d227Schristos will be a valid file name yet not exist when @code{tmpnam} checks for
7*bb16d227Schristos it.  @var{s} must point to a buffer of at least @code{L_tmpnam} bytes,
8*bb16d227Schristos or be @code{NULL}.  Use of this function creates a security risk, and it must
9*bb16d227Schristos not be used in new projects.  Use @code{mkstemp} instead.
10*bb16d227Schristos 
11*bb16d227Schristos @end deftypefn
12*bb16d227Schristos 
13*bb16d227Schristos */
14*bb16d227Schristos 
15*bb16d227Schristos #include <stdio.h>
16*bb16d227Schristos 
17*bb16d227Schristos #ifndef L_tmpnam
18*bb16d227Schristos #define L_tmpnam 100
19*bb16d227Schristos #endif
20*bb16d227Schristos #ifndef P_tmpdir
21*bb16d227Schristos #define P_tmpdir "/usr/tmp"
22*bb16d227Schristos #endif
23*bb16d227Schristos 
24*bb16d227Schristos static char tmpnam_buffer[L_tmpnam];
25*bb16d227Schristos static int tmpnam_counter;
26*bb16d227Schristos 
27*bb16d227Schristos extern int getpid (void);
28*bb16d227Schristos 
29*bb16d227Schristos char *
tmpnam(char * s)30*bb16d227Schristos tmpnam (char *s)
31*bb16d227Schristos {
32*bb16d227Schristos   int pid = getpid ();
33*bb16d227Schristos 
34*bb16d227Schristos   if (s == NULL)
35*bb16d227Schristos     s = tmpnam_buffer;
36*bb16d227Schristos 
37*bb16d227Schristos   /*  Generate the filename and make sure that there isn't one called
38*bb16d227Schristos       it already.  */
39*bb16d227Schristos 
40*bb16d227Schristos   while (1)
41*bb16d227Schristos     {
42*bb16d227Schristos       FILE *f;
43*bb16d227Schristos       sprintf (s, "%s/%s%x.%x", P_tmpdir, "t", pid, tmpnam_counter);
44*bb16d227Schristos       f = fopen (s, "r");
45*bb16d227Schristos       if (f == NULL)
46*bb16d227Schristos 	break;
47*bb16d227Schristos       tmpnam_counter++;
48*bb16d227Schristos       fclose (f);
49*bb16d227Schristos     }
50*bb16d227Schristos 
51*bb16d227Schristos   return s;
52*bb16d227Schristos }
53