1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
| | #include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
#include "libc.h"
char *__mktemp(char *);
int __gen_tempname (char *template, int len, int flags)
{
if (len < 0) return EINVAL;
int templen = strlen(template)-len;
if (templen<6) return EINVAL;
char *suffix = (char *)malloc((len+1)*sizeof(char));
/* Copy the last len chars plus the null termination */
int i;
for (i = 0; i <= len; i++)
suffix[i] = template[templen+i];
/* Null terminate the template before the suffice */
template[templen] = '\0';
int fd, retries = 100, t0 = *template;
while (retries--) {
if (!*__mktemp(template)) return -1;
/* Copy back the suffix */
for (i = 0; i <= len; i++)
template[templen+i] = suffix[i];
if ((fd = open(template, flags | O_CREAT | O_EXCL, 0600))>=0)
return fd;
if (errno != EEXIST) return -1;
/* this is safe because mktemp verified
* that we have a valid template string */
template[0] = t0;
strcpy(template+templen-6, "XXXXXX");
}
return -1;
}
|