1 /* 2 * mkstemp(): create a unique temporary file 3 * written by Cornelius Krasel - (c) 2000 4 * bugfixes by Matthias Andree - (c) 2001 - 2002 5 * 6 * See COPYING for restrictions on the use of this software. 7 */ 8 9 #include "config.h" 10 #include "system.h" 11 #if !HAVE_MKSTEMP 12 13 #include <string.h> 14 #include <errno.h> 15 #include <sys/types.h> 16 #include <sys/stat.h> 17 #include <fcntl.h> 18 #include <stdlib.h> 19 20 #ifdef WITH_DMALLOC 21 #include <dmalloc.h> 22 #endif 23 24 #define ATTEMPTS 5 25 26 int 27 mkstemp(char *template) 28 { 29 int i, j, fd; 30 char *c; 31 char use[] = /* 62 chars to choose from */ 32 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 33 34 c = (template + strlen(template) - 1); 35 i = 0; 36 while ((*c-- == 'X') && (*c != *template)) 37 i++; 38 if (i < 6) 39 /* less than 6 X's */ 40 return EINVAL; 41 i = 0; 42 while (i < ATTEMPTS) { 43 srand((unsigned int)(time(NULL) + i)); 44 /* initialize random number generator */ 45 for (j = 0; j < 6; j++) { 46 /* generate 0<x<61 from the random number and use it as index */ 47 *(c + j + 1) = use[(int)(62.0 * rand() / (RAND_MAX + 1.0))]; 48 } 49 fd = open(template, O_RDWR | O_EXCL | O_CREAT, 0600); 50 if (fd >= 0) 51 return fd; /* success */ 52 i++; 53 } 54 return EEXIST; /* we failed */ 55 } 56 #endif /* HAVE_MKSTEMP */ 57 /* ANSI C forbids an empty source file... */ 58 static void 59 dummy_func(void) 60 { 61 dummy_func(); 62 }