tmpnam.c revision 89857
189857Sobrien/*
289857Sobrien
389857Sobrien@deftypefn Supplemental char* tmpnam (char *@var{s})
489857Sobrien
589857SobrienThis function attempts to create a name for a temporary file, which
689857Sobrienwill be a valid file name yet not exist when @code{tmpnam} checks for
789857Sobrienit.  @var{s} must point to a buffer of at least @code{L_tmpnam} bytes,
889857Sobrienor be @code{NULL}.  Use of this function creates a security risk, and it must
989857Sobriennot be used in new projects.  Use @code{mkstemp} instead.
1089857Sobrien
1189857Sobrien@end deftypefn
1289857Sobrien
1389857Sobrien*/
1489857Sobrien
1533965Sjdp#include <stdio.h>
1633965Sjdp
1733965Sjdp#ifndef L_tmpnam
1860484Sobrien#define L_tmpnam 100
1933965Sjdp#endif
2033965Sjdp#ifndef P_tmpdir
2133965Sjdp#define P_tmpdir "/usr/tmp"
2233965Sjdp#endif
2333965Sjdp
2433965Sjdpstatic char tmpnam_buffer[L_tmpnam];
2533965Sjdpstatic int tmpnam_counter;
2633965Sjdp
2733965Sjdpextern int getpid ();
2833965Sjdp
2933965Sjdpchar *
3033965Sjdptmpnam (s)
3133965Sjdp     char *s;
3233965Sjdp{
3333965Sjdp  int pid = getpid ();
3433965Sjdp
3533965Sjdp  if (s == NULL)
3633965Sjdp    s = tmpnam_buffer;
3733965Sjdp
3833965Sjdp  /*  Generate the filename and make sure that there isn't one called
3933965Sjdp      it already.  */
4033965Sjdp
4133965Sjdp  while (1)
4233965Sjdp    {
4333965Sjdp      FILE *f;
4433965Sjdp      sprintf (s, "%s/%s%x.%x", P_tmpdir, "t", pid, tmpnam_counter);
4533965Sjdp      f = fopen (s, "r");
4633965Sjdp      if (f == NULL)
4733965Sjdp	break;
4833965Sjdp      tmpnam_counter++;
4933965Sjdp      fclose (f);
5033965Sjdp    }
5133965Sjdp
5233965Sjdp  return s;
5333965Sjdp}
54