Update.
[glibc.git] / sysdeps / posix / mkstemp.c
blobf0db5d5d5324b963ff052d88e6922a060718d87e
1 /* Copyright (C) 1991, 1992, 1996, 1998 Free Software Foundation, Inc.
2 This file is part of 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. */
19 #include <stdlib.h>
20 #include <string.h>
21 #include <errno.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <fcntl.h>
25 #include <unistd.h>
26 #include <sys/time.h>
28 /* Generate a unique temporary file name from TEMPLATE.
29 The last six characters of TEMPLATE must be "XXXXXX";
30 they are replaced with a string that makes the filename unique.
31 Returns a file descriptor open on the file for reading and writing. */
32 int
33 mkstemp (template)
34 char *template;
36 static const char letters[]
37 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
38 static uint64_t value;
39 struct timeval tv;
40 char *XXXXXX;
41 size_t len;
42 int count;
44 len = strlen (template);
45 if (len < 6 || strcmp (&template[len - 6], "XXXXXX"))
47 __set_errno (EINVAL);
48 return -1;
51 /* This is where the Xs start. */
52 XXXXXX = &template[len - 6];
54 /* Get some more or less random data. */
55 __gettimeofday (&tv, NULL);
56 value += ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
58 for (count = 0; count < TMP_MAX; ++count)
60 uint64_t v = value;
61 int fd;
63 /* Fill in the random bits. */
64 XXXXXX[0] = letters[v % 62];
65 v /= 62;
66 XXXXXX[1] = letters[v % 62];
67 v /= 62;
68 XXXXXX[2] = letters[v % 62];
69 v /= 62;
70 XXXXXX[3] = letters[v % 62];
71 v /= 62;
72 XXXXXX[4] = letters[v % 62];
73 v /= 62;
74 XXXXXX[5] = letters[v % 62];
76 fd = open (template, O_RDWR|O_CREAT|O_EXCL, 0600);
77 if (fd >= 0)
78 /* The file does not exist. */
79 return fd;
81 /* This is a random value. It is only necessary that the next
82 TMP_MAX values generated by adding 7777 to VALUE are different
83 with (module 2^32). */
84 value += 7777;
87 /* We return the null string if we can't find a unique file name. */
88 template[0] = '\0';
89 return -1;