- HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
- if (h == INVALID_HANDLE_VALUE)
- goto fail;
+ if (GetLastError() != ERROR_ACCESS_DENIED)
+ goto err_set_errno;
+
+ /* We can work around the above-mentioned problem by renaming the
+ * destination file to yet another temporary file, then "deleting" it,
+ * which on Windows will in fact not actually delete it immediately but
+ * rather mark it for deletion when the last handle to it is closed. */
+ {
+ static const wchar_t orig_suffix[5] = L".orig";
+ const size_t num_rand_chars = 9;
+ wchar_t *p;
+
+ size_t dstlen = wcslen(dstpath);
+
+ tmpname = alloca(sizeof(wchar_t) *
+ (dstlen + ARRAY_LEN(orig_suffix) + num_rand_chars + 1));
+ p = tmpname;
+ p = wmempcpy(p, dstpath, dstlen);
+ p = wmempcpy(p, orig_suffix, ARRAY_LEN(orig_suffix));
+ randomize_char_array_with_alnum(p, num_rand_chars);
+ p += num_rand_chars;
+ *p = L'\0';
+ }