c0e06f5ef424216c3b142999942b1146c801fa4d
[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;
17
18         if (l < 6 || strcmp(template+l-6, "XXXXXX")) {
19                 errno = EINVAL;
20                 *template = 0;
21                 return template;
22         }
23         while (retries--) {
24                 clock_gettime(CLOCK_REALTIME, &ts);
25                 r = ts.tv_nsec + (uintptr_t)&ts / 16 + (uintptr_t)template;
26                 for (i=1; i<=6; i++, r>>=4)
27                         template[l-i] = 'A'+(r&15);
28                 if (access(template, F_OK) < 0) return template;
29         }
30         *template = 0;
31         errno = EEXIST;
32         return template;
33 }
34
35 weak_alias(__mktemp, mktemp);