summaryrefslogtreecommitdiff
path: root/libc/stdlib/mkstemp.c
blob: d65ada4f738c0361e288b8473085d381f70db01d (plain)
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
43

#include <features.h>
#include <unistd.h>
#include <fcntl.h>

int mkstemp(template)
char * template;
{
	int i;
	int num; /* UNINITIALIZED */
	int n2;
	int l = strlen(template);
	
	if (l<6) {
		errno = EINVAL;
		return -1;
	}
	
	for(i=l-6;i<l;i++)
		if (template[i] != 'X') {
			errno = EINVAL;
			return -1;
		}
	
again:	
	n2 = num;
	for(i=l-1;i>=l-6;i--) {
		template[i] = '0' + n2 % 10;
		n2 /= 10;
	}
	
	i = open(template, O_RDWR|O_EXCL|O_CREAT, 0666);
	
	if (i==-1) {
		if (errno == EEXIST) {
			num++;
			goto again;
		} else
			return -1;
	}
	
	return i;
}