Merge branch 'master' of git://git.ucc.asn.au/tpg/acess2
[tpg/acess2.git] / Usermode / Libraries / libposix.so_src / mktemp.c
1 /*
2  * Acess2 POSIX Emulation Layer
3  * - By John Hodge
4  * 
5  * mkstemp.c
6  * - mkstemp/mktemp
7  */
8 #include <unistd.h>     // mktemp
9 #include <stdlib.h>     // mkstemp
10 #include <stdio.h>
11 #include <string.h>     // str*
12 #include <errno.h>
13
14 // === CODE ===
15 int mkstemp(char *template)
16 {
17         size_t  tpl_len = strlen(template);
18         if( tpl_len < 6 ) {
19                 errno = EINVAL;
20                 return -1;
21         }
22         if( strcmp(template+tpl_len-6, "XXXXXX") != 0 ) {
23                 errno = EINVAL;
24                 return -1;
25         }
26         
27         for( int i = 0; i < 1000000; i ++ )
28         {
29                 snprintf(template+tpl_len-6, 6+1, "%06d", i);
30                 int fd = open(template, O_EXCL|O_CREAT, 0600);
31                 if(fd == -1)    continue ;
32         
33                 return fd;
34         }
35         
36         errno = EEXIST;
37         template[0] = '\0';
38         return -1;
39 }
40
41 char *mktemp(char *template)
42 {
43          int fd = mkstemp(template);
44         if( fd == -1 )
45                 return NULL;
46         close(fd);
47         return template;
48 }
49
50

UCC git Repository :: git.ucc.asn.au