1 /* Create a temporary file.
2 Copyright (C) 2007, 2009-2018 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 Ben Pfaff. */
24 /* This replacement is used only on native Windows platforms. */
33 #define WIN32_LEAN_AND_MEAN /* avoid including junk */
40 /* PATH_MAX is guaranteed to be defined, because this replacement is only
41 used on native Windows. */
43 /* On Windows, opening a file with _O_TEMPORARY has the effect of passing
44 the FILE_FLAG_DELETE_ON_CLOSE flag to CreateFile(), which has the effect
45 of deleting the file when it is closed - even when the program crashes.
46 But (according to the Cygwin sources) it works only on Windows NT or newer.
47 So we cache the info whether we are running on Windows NT or newer. */
50 supports_delete_on_close ()
52 static int known
; /* 1 = yes, -1 = no, 0 = unknown */
58 <https://msdn.microsoft.com/en-us/library/ms724451.aspx>
59 this structure must be initialized as follows: */
60 v
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFO
);
62 if (GetVersionEx (&v
))
63 known
= (v
.dwPlatformId
== VER_PLATFORM_WIN32_NT
? 1 : -1);
76 /* Find Windows temporary file directory.
77 We provide this as the directory argument to path_search because Windows
78 defines P_tmpdir to "\\" and will therefore try to put all temporary files
79 in the root directory (unless $TMPDIR is set). */
80 retval
= GetTempPath (PATH_MAX
, dir
);
81 if (retval
> 0 && retval
< PATH_MAX
)
83 char xtemplate
[PATH_MAX
];
85 if (path_search (xtemplate
, PATH_MAX
, dir
, NULL
, true) >= 0)
87 size_t len
= strlen (xtemplate
);
88 int o_temporary
= (supports_delete_on_close () ? _O_TEMPORARY
: 0);
93 memcpy (&xtemplate
[len
- 6], "XXXXXX", 6);
94 if (gen_tempname (xtemplate
, 0, 0, GT_NOCREATE
) < 0)
100 fd
= _open (xtemplate
,
101 _O_CREAT
| _O_EXCL
| o_temporary
102 | _O_RDWR
| _O_BINARY
,
103 _S_IREAD
| _S_IWRITE
);
105 while (fd
< 0 && errno
== EEXIST
);
109 FILE *fp
= _fdopen (fd
, "w+b");
115 int saved_errno
= errno
;
125 errno
= ENAMETOOLONG
;
127 /* Ideally this should translate GetLastError () to an errno value. */