make mkdtemp and mkstemp family leave template unchanged on fail
[musl] / src / temp / mkdtemp.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 <sys/stat.h>
9 #include "libc.h"
10
11 char *__randname(char *);
12
13 char *mkdtemp(char *template)
14 {
15         size_t l = strlen(template);
16         int retries = 100;
17
18         if (l<6 || memcmp(template+l-6, "XXXXXX", 6)) {
19                 errno = EINVAL;
20                 return 0;
21         }
22
23         do {
24                 __randname(template+l-6);
25                 if (!mkdir(template, 0700)) return template;
26         } while (--retries && errno == EEXIST);
27
28         memcpy(template+l-6, "XXXXXX", 6);
29         return 0;
30 }