File: mkstemp.c

package info (click to toggle)
dact 0.8.42-6
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,444 kB
  • sloc: ansic: 5,923; sh: 2,748; makefile: 116
file content (53 lines) | stat: -rw-r--r-- 1,627 bytes parent folder | download | duplicates (6)
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
44
45
46
47
48
49
50
51
52
53
/*
 * NAME
 *        mkstemp - create a unique temporary file
 * 
 * SYNOPSIS
 *        int mkstemp(char *template);
 *
 * DESCRIPTION
 *        The mkstemp() function generates a unique temporary file name from tem-
 *        plate.  The last six characters of template must be  XXXXXX  and  these
 *        are  replaced with a string that makes the filename unique. The file is
 *        then created with mode read/write  and permissions 0600.  Since it will
 *        be modified,  template  must not  be a string  constant, but  should be
 *        declared as a character array. The file is opened with the O_EXCL flag, 
 *        guaranteeing  that when mkstemp  returns successfully  we are  the only
 *        user.
 *
 * RETURN VALUE
 *        The mkstemp() function returns the file descriptor fd of the  temporary
 *        file or -1 on error.
 *
 * ERRORS
 *        EINVAL The  last  six characters of template were not XXXXXX.  Now tem-
 *               plate is unchanged.
 *
 *        EEXIST Could not create a unique temporary filename.  Now the  contents
 *               of template are undefined.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

int mkstemp(char *template) {
	int retfd=-1;
	int i, temp_len;

	temp_len=strlen(template);
	if (temp_len<6) return(-1);
	if (strcmp(template+(temp_len-6), "XXXXXX")!=0) return(-1);

	srand(getpid()+temp_len);
	for (i=0; i<6; i++) {
		template[temp_len-i-1]='A'+((rand()+i)%26);
		retfd=open(template, O_EXCL|O_CREAT|O_RDWR, 0600);
		if (retfd>=0) break;
	}
	
	return(retfd);
}