xref: /plan9/sys/src/ape/lib/bsd/mktemp.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 #include <stdlib.h>
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include <stdio.h>
7 
8 char*
mktemp(char * template)9 mktemp(char *template)
10 {
11 	int n;
12 	long x;
13 	char *p;
14 	int c;
15 	struct stat stbuf;
16 
17 	n = strlen(template);
18 	p = template+n-6;
19 	if (n < 6 || strcmp(p, "XXXXXX") != 0) {
20 		*template = 0;
21 	} else {
22 		x = getpid() % 100000;
23 		sprintf(p, "%05d", x);
24 		p += 5;
25 		for(c = 'a'; c <= 'z'; c++) {
26 			*p = c;
27 			if (stat(template, &stbuf) < 0)
28 				return template;
29 		}
30 		*template = 0;
31 	}
32 	return template;
33 }
34