1 /* Copyright (C) 1991, 1992, 1996, 1998 Free Software Foundation, Inc.
2 This file is derived from mkstemp.c from the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details.
14 You should have received a copy of the GNU Library General Public
15 License along with the GNU C Library; see the file COPYING.LIB. If not,
16 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 Boston, MA 02111-1307, USA. */
40 #include "gansidecl.h"
43 /* We need to provide a type for gcc_uint64_t. */
45 typedef unsigned long long gcc_uint64_t;
47 typedef unsigned long gcc_uint64_t;
54 /* Generate a unique temporary file name from TEMPLATE.
56 TEMPLATE has the form:
58 <path>/ccXXXXXX<suffix>
60 SUFFIX_LEN tells us how long <suffix> is (it can be zero length).
62 The last six characters of TEMPLATE before <suffix> must be "XXXXXX";
63 they are replaced with a string that makes the filename unique.
65 Returns a file descriptor open on the file for reading and writing. */
67 mkstemps (template, suffix_len)
71 static const char letters[]
72 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
73 static gcc_uint64_t value;
74 #ifdef HAVE_GETTIMEOFDAY
81 len = strlen (template);
83 if (len < 6 + suffix_len
84 || strncmp (&template[len - 6 - suffix_len], "XXXXXX", 6))
89 XXXXXX = &template[len - 6 - suffix_len];
91 #ifdef HAVE_GETTIMEOFDAY
92 /* Get some more or less random data. */
93 gettimeofday (&tv, NULL);
94 value += ((gcc_uint64_t) tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
99 for (count = 0; count < TMP_MAX; ++count)
101 gcc_uint64_t v = value;
104 /* Fill in the random bits. */
105 XXXXXX[0] = letters[v % 62];
107 XXXXXX[1] = letters[v % 62];
109 XXXXXX[2] = letters[v % 62];
111 XXXXXX[3] = letters[v % 62];
113 XXXXXX[4] = letters[v % 62];
115 XXXXXX[5] = letters[v % 62];
117 fd = open (template, O_RDWR|O_CREAT|O_EXCL, 0600);
119 /* The file does not exist. */
122 /* This is a random value. It is only necessary that the next
123 TMP_MAX values generated by adding 7777 to VALUE are different
124 with (module 2^32). */
128 /* We return the null string if we can't find a unique file name. */