initial check-in, version 0.5.0
[musl] / src / stdio / tempnam.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <fcntl.h>
5 #include <unistd.h>
6 #include <limits.h>
7 #include <errno.h>
8 #include "libc.h"
9
10 char *tempnam(const char *dir, const char *pfx)
11 {
12         static int lock;
13         static int index;
14         char *s;
15         int pid = getpid();
16         int l;
17
18         if (!dir) dir = P_tmpdir;
19         if (!pfx) pfx = "temp";
20
21         if (access(dir, R_OK|W_OK|X_OK) != 0)
22                 return NULL;
23
24         l = strlen(dir) + 1 + strlen(pfx) + 2 + sizeof(int)*3*2 + 1;
25         s = malloc(l);
26         if (!s) {
27                 errno = ENOMEM;
28                 return NULL;
29         }
30
31         LOCK(&lock);
32         for (; index < TMP_MAX; index++) {
33                 snprintf(s, l, "%s/%s-%d-%d", dir, pfx, pid, index);
34                 if (access(s, F_OK) != 0) {
35                         UNLOCK(&lock);
36                         return s;
37                 }
38         }
39         UNLOCK(&lock);
40         free(s);
41         return NULL;    
42 }