1462a16c6dd189ff8354656a924bfcc324ddc67b
[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 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                 return 0;
21         }
22         clock_gettime(CLOCK_REALTIME, &ts);
23         r = ts.tv_nsec + (uintptr_t)&ts / 16 + (uintptr_t)template;
24         while (retries--) {
25                 snprintf(template+l-6, 7, "%06lX", r & 0xffffff);
26                 if (access(template, F_OK) < 0) return template;
27                 r = r * 1103515245 + 12345;
28         }
29         errno = EEXIST;
30         return 0;
31 }
32
33 weak_alias(__mktemp, mktemp);