I believe this is covered in Windows Internals. The short story is that even though you've called CloseHandle on the file handle, the kernel may still have outstanding references that take a few milliseconds to close.
A more reliable way to delete the file when you're done is to use the FILE_FLAG_DELETE_ON_CLOSE flag when opening the last handle. This works even better if you can avoid closing the file between reads/writes.
#include <windows.h>
#include <stdio.h>
int wmain(int argc, wchar_t** argv)
{
LPCWSTR fileName = L"c:\\temp\\test1234.bin";
HANDLE h1 = CreateFileW(
fileName,
GENERIC_WRITE,
// make sure the next call to CreateFile can succeed if this handle hasn't been closed yet
FILE_SHARE_READ | FILE_SHARE_DELETE,
NULL,
CREATE_ALWAYS,
FILE_FLAG_SEQUENTIAL_SCAN | FILE_ATTRIBUTE_TEMPORARY,
NULL);
if (h1 == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "h1 failed: 0x%x\n", GetLastError());
return GetLastError();
}
HANDLE h2 = CreateFileW(
fileName,
GENERIC_READ,
// FILE_SHARE_WRITE is required in case h1 with GENERIC_WRITE access is still open
FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
// tell the OS to delete the file as soon as it is closed, no DeleteFile call needed
FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_SEQUENTIAL_SCAN | FILE_ATTRIBUTE_TEMPORARY,
NULL);
if (h2 == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "h2 failed: 0x%x\n", GetLastError());
return GetLastError();
}
return 0;
}