Creo que esto está cubierto en Windows Internals. La historia corta es que, aunque haya llamado a CloseHandle en el manejador de archivos, el kernel puede tener referencias pendientes que tarden unos pocos milisegundos en cerrarse.
Una manera más confiable de eliminar el archivo cuando haya terminado es utilizar el indicador FILE_FLAG_DELETE_ON_CLOSE al abrir el último identificador. Esto funciona incluso mejor si puede evitar cerrar el archivo entre lecturas/escrituras.
#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;
}
¿Seguro que está cerrando el archivo correctamente antes de intentar eliminarla? ¿Te perdiste alguna manija? – RageZ
Como dije, incluso lo comprobé con las herramientas de WinInternals. Todas las aperturas están emparejadas con closes, pero la eliminación falla. Y agregar dormir durante 1 segundo soluciona el problema. –
Puede que las ventanas tengan errores, pero estoy un poco dudoso sobre eso. si agrega 'sleep', hágala funcionar debería estar bien ^^ – RageZ