File: mkstemp.c

package info (click to toggle)
leafnode 1.11.11-1
  • links: PTS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 2,468 kB
  • sloc: ansic: 10,914; sh: 1,748; xml: 628; makefile: 291; perl: 84; sed: 4
file content (62 lines) | stat: -rw-r--r-- 1,352 bytes parent folder | download | duplicates (8)
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
54
55
56
57
58
59
60
61
62
/*
 * mkstemp(): create a unique temporary file
 * written by Cornelius Krasel - (c) 2000
 * bugfixes by Matthias Andree - (c) 2002
 *
 * See COPYING for restrictions on the use of this software.
 */

#include "config.h"
#include "system.h"
#if !HAVE_MKSTEMP

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

#ifdef WITH_DMALLOC
#include <dmalloc.h>
#endif

#define ATTEMPTS 5

int
mkstemp(char *template)
{
    int i, j, fd;
    char *c;
    char use[] =		/* 62 chars to choose from */
	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    c = (template + strlen(template) - 1);
    i = 0;
    while ((*c-- == 'X') && (*c != *template))
	i++;
    if (i < 6)
	/* less than 6 X's */
	return EINVAL;
    i = 0;
    while (i < ATTEMPTS) {
	srand((unsigned int)(time(NULL) + i));
	/* initialize random number generator */
	for (j = 0; j < 6; j++) {
	    /* generate 0<x<61 from the random number and use it as index */
	    *(c + j + 1) = use[(int)(62.0 * rand() / (RAND_MAX + 1.0))];
	}
	fd = open(template, O_RDWR | O_EXCL | O_CREAT, 0600);
	if (fd >= 0)
	    return fd;		/* success */
	i++;
    }
    return EEXIST;		/* we failed */
}
#endif				/* HAVE_MKSTEMP */
/* ANSI C forbids an empty source file... */
static void
dummy_func(void)
{
    dummy_func();
}