Fix last ChangeLog entry.
[gnulib.git] / tests / test-tempname.c
blobb9e51978be9aef5cc5e3767489763549203bb1b1
1 /* Test of creating a temporary file.
2 Copyright (C) 2022-2025 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program 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
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Written by Bruno Haible <bruno@clisp.org>, 2022. */
19 #include <config.h>
21 #include "tempname.h"
23 #include <string.h>
24 #include <unistd.h>
26 #include "macros.h"
28 int
29 main ()
31 /* Verify that two consecutive calls to gen_tempname return two different
32 file names, with a high probability. */
33 const char *templ18 = "gl-temp-XXXXXX.xyz";
34 char filename1[18 + 1];
35 char filename2[18 + 1];
37 /* Case 1: The first file still exists while gen_tempname is called a second
38 time. */
40 strcpy (filename1, templ18);
41 int fd1 = gen_tempname (filename1, strlen (".xyz"), 0, GT_FILE);
42 ASSERT (fd1 >= 0);
44 strcpy (filename2, templ18);
45 int fd2 = gen_tempname (filename2, strlen (".xyz"), 0, GT_FILE);
46 ASSERT (fd2 >= 0);
48 /* gen_tempname arranges (via O_EXCL) to not return the name of an existing
49 file. */
50 ASSERT (strcmp (filename1, filename2) != 0);
52 /* Clean up. */
53 close (fd1);
54 close (fd2);
55 unlink (filename1);
56 unlink (filename2);
59 /* Case 2: The first file is deleted before gen_tempname is called a second
60 time. */
62 strcpy (filename1, templ18);
63 int fd1 = gen_tempname (filename1, strlen (".xyz"), 0, GT_FILE);
64 ASSERT (fd1 >= 0);
66 /* Clean up. */
67 close (fd1);
68 unlink (filename1);
70 strcpy (filename2, templ18);
71 int fd2 = gen_tempname (filename2, strlen (".xyz"), 0, GT_FILE);
72 ASSERT (fd2 >= 0);
74 /* With 6 'X' and a good pseudo-random number generator behind the scenes,
75 the probability of getting the same file name twice in a row should be
76 1/62^6 < 1/10^10.
77 But on 64-bit native Windows, this probability is ca. 0.1% to 0.3%. */
78 ASSERT (strcmp (filename1, filename2) != 0);
80 /* Clean up. */
81 close (fd2);
82 unlink (filename2);
85 return test_exit_status;