home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / dmake40.zip / unix / bsd43 / tempnam.c < prev    next >
C/C++ Source or Header  |  1994-10-23  |  2KB  |  79 lines

  1. /*LINTLIBRARY*/
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5.  
  6. #define max(A,B) (((A)<(B))?(B):(A))
  7.  
  8. extern char *mktemp();
  9. extern int access();
  10.  
  11. static char *cpdir();
  12. static char  seed[4]="AAA";
  13.  
  14. /* BSD stdio.h doesn't define P_tmpdir, so let's do it here */
  15. #ifndef P_tmpdir
  16. static char *P_tmpdir = "/tmp";
  17. #endif
  18.  
  19. char *
  20. tempnam(dir, prefix)
  21. char *dir;        /* use this directory please (if non-NULL) */
  22. char *prefix;        /* use this (if non-NULL) as filename prefix */
  23. {
  24.    register char *p, *q, *tmpdir;
  25.    int            tl=0, dl=0, pl;
  26.  
  27.    pl = strlen(P_tmpdir);
  28.  
  29.    if( (tmpdir = getenv("TMPDIR")) != NULL ) tl = strlen(tmpdir);
  30.    if( dir != NULL ) dl = strlen(dir);
  31.  
  32.    if( (p = malloc((unsigned)(max(max(dl,tl),pl)+16))) == NULL )
  33.      return(NULL);
  34.  
  35.    *p = '\0';
  36.  
  37.    if( (tl == 0) || (access( cpdir(p, tmpdir), 3) != 0) )
  38.      if( (dl == 0) || (access( cpdir(p, dir), 3) != 0) )
  39.     if( access( cpdir(p, P_tmpdir),   3) != 0 )
  40.        if( access( cpdir(p, "/tmp"),  3) != 0 )
  41.           return(NULL);
  42.  
  43.    (void) strcat(p, "/");
  44.    if(prefix)
  45.    {
  46.       *(p+strlen(p)+5) = '\0';
  47.       (void)strncat(p, prefix, 5);
  48.    }
  49.  
  50.    (void)strcat(p, seed);
  51.    (void)strcat(p, "XXXXXX");
  52.  
  53.    q = seed;
  54.    while(*q == 'Z') *q++ = 'A';
  55.    ++*q;
  56.  
  57.    if(*mktemp(p) == '\0') return(NULL);
  58.    return(p);
  59. }
  60.  
  61.  
  62.  
  63. static char *
  64. cpdir(buf, str)
  65. char *buf;
  66. char *str;
  67. {
  68.    char *p;
  69.  
  70.    if(str != NULL)
  71.    {
  72.       (void) strcpy(buf, str);
  73.       p = buf - 1 + strlen(buf);
  74.       if(*p == '/') *p = '\0';
  75.    }
  76.  
  77.    return(buf);
  78. }
  79.