a390d4272cef638384973268ba149b99fbcf01ed
[musl] / src / temp / mkstemp.c
1 #include <string.h>
2 #include <stdio.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 *__mktemp(char *);
11
12 int mkstemp(char *template)
13 {
14         int fd, retries = 100, t0 = *template;
15         while (retries--) {
16                 if (!*__mktemp(template)) return -1;
17                 if ((fd = open(template, O_RDWR | O_CREAT | O_EXCL, 0600))>=0)
18                         return fd;
19                 if (errno != EEXIST) return -1;
20                 /* this is safe because mktemp verified
21                  * that we have a valid template string */
22                 template[0] = t0;
23                 strcpy(template+strlen(template)-6, "XXXXXX");
24         }
25         return -1;
26 }
27
28 LFS64(mkstemp);