b04f5dee7ec7565a635799dc32cd13e9c4c4ed79
[musl] / src / temp / mktemp.c
1 #include <string.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <fcntl.h>
5 #include <unistd.h>
6 #include <errno.h>
7 #include <time.h>
8 #include <stdint.h>
9 #include "libc.h"
10
11 char *__mktemp(char *template)
12 {
13         struct timespec ts;
14         size_t i, l = strlen(template);
15         int retries = 10000;
16         unsigned long r, t;
17
18         if (l < 6 || strcmp(template+l-6, "XXXXXX")) {
19                 errno = EINVAL;
20                 *template = 0;
21                 return template;
22         }
23         clock_gettime(CLOCK_REALTIME, &ts);
24         r = ts.tv_nsec + (uintptr_t)&ts / 16 + (uintptr_t)template;
25         while (retries--) {
26                 for (t=r, i=1; i<=6; i++, t>>=4)
27                         template[l-i] = 'A'+(t&15);
28                 if (access(template, F_OK) < 0) return template;
29                 r = r * 1103515245 + 12345;
30         }
31         *template = 0;
32         errno = EEXIST;
33         return template;
34 }
35
36 weak_alias(__mktemp, mktemp);