1 /* 2 * NAME 3 * mkstemp - create a unique temporary file 4 * 5 * SYNOPSIS 6 * int mkstemp(char *template); 7 * 8 * DESCRIPTION 9 * The mkstemp() function generates a unique temporary file name from tem- 10 * plate. The last six characters of template must be XXXXXX and these 11 * are replaced with a string that makes the filename unique. The file is 12 * then created with mode read/write and permissions 0600. Since it will 13 * be modified, template must not be a string constant, but should be 14 * declared as a character array. The file is opened with the O_EXCL flag, 15 * guaranteeing that when mkstemp returns successfully we are the only 16 * user. 17 * 18 * RETURN VALUE 19 * The mkstemp() function returns the file descriptor fd of the temporary 20 * file or -1 on error. 21 * 22 * ERRORS 23 * EINVAL The last six characters of template were not XXXXXX. Now tem- 24 * plate is unchanged. 25 * 26 * EEXIST Could not create a unique temporary filename. Now the contents 27 * of template are undefined. 28 */ 29 30 #include <sys/types.h> 31 #include <sys/stat.h> 32 #include <stdlib.h> 33 #include <unistd.h> 34 #include <string.h> 35 #include <fcntl.h> 36 37 int mkstemp(char *template) { 38 int retfd=-1; 39 int i, temp_len; 40 41 temp_len=strlen(template); 42 if (temp_len<6) return(-1); 43 if (strcmp(template+(temp_len-6), "XXXXXX")!=0) return(-1); 44 45 srand(getpid()+temp_len); 46 for (i=0; i<6; i++) { 47 template[temp_len-i-1]='A'+((rand()+i)%26); 48 retfd=open(template, O_EXCL|O_CREAT|O_RDWR, 0600); 49 if (retfd>=0) break; 50 } 51 52 return(retfd); 53 } |