問題は、ファイルのハンドルを取得しているのはあなただけではないということです。他のプロセスやサービスもファイルを開くことができます。したがって、ハンドルを解放するまで削除することはできません。これらのハンドルが開いているときに、ファイルの名前を変更できます。これらのハンドルが開いている間にファイルをコピーできます。ただし、ファイルを別のコンテナに移動できるかどうかわかりませんか?
その他のプロセスとサービス、特に。ウイルス対策、インデックス作成などを含みます。
これは、Windowsで「即時削除」を実行するために作成した関数です。
bool DeleteFileNow(const wchar_t * filename)
{
// don't do anything if the file doesn't exist!
if (!PathFileExistsW(filename))
return false;
// determine the path in which to store the temp filename
wchar_t path[MAX_PATH];
wcscpy_s(path, filename);
PathRemoveFileSpecW(path);
// generate a guaranteed to be unique temporary filename to house the pending delete
wchar_t tempname[MAX_PATH];
if (!GetTempFileNameW(path, L".xX", 0, tempname))
return false;
// move the real file to the dummy filename
if (!MoveFileExW(filename, tempname, MOVEFILE_REPLACE_EXISTING))
{
// clean up the temp file
DeleteFileW(tempname);
return false;
}
// queue the deletion (the OS will delete it when all handles (ours or other processes) close)
return DeleteFileW(tempname) != FALSE;
}