我用 FILE_FLAG_DELETE_ON_CLOSE 打开了文件,但现在我改变主意了I opened a file with FILE_FLAG_DELETE_ON_CLOSE, but now I changed my mind
在 Windows 编程中,如果开发者使用 `FILE_FLAG_DELETE_ON_CLOSE` 标志打开文件,系统会在文件关闭时自动将其删除。然而,一旦设置了该标志,开发者无法直接“改变主意”撤销这一删除行为。微软官方博客指出,解决这个问题的唯一方法是采用不同的实现思路,而不是试图在运行时重置标志。文章探讨了这一 Windows API 机制背后的底层逻辑,并提供了在需要条件性删除文件时的正确替代方案。
Raymond Chen
The CreateFile function has a flag called FILE_FLAG_DELETE_ON_CLOSE, which means that the file will be deleted when the last handle to the file is closed. But what if you pass that flag and then change your mind? Is there a way to call take-backs?
No, there are no take-backs. The FILE_FLAG_DELETE_ON_CLOSE flag is permanent.
So what do you do if you want to make a file deleted when the last handle is closed, but only based on some condition determined later?
What you can do is open the file normally, and then once you realize that you want to delete it on last close, you can turn the “delete on close” flag on.
BOOL MarkFileAsDeleteOnClose(HANDLE file)
{
FILE_DISPOSITION_INFO info{};
info.DeleteFile = TRUE;
return SetFileInformationByHandle(hfile,
FileDispositionInfo, &info, sizeof(info));Unlike FILE_FLAG_DELETE_ON_CLOSE, you can take back the DeleteFile disposition.
BOOL MarkFileAsNoLongerDeleteOnClose(HANDLE file)
{
FILE_DISPOSITION_INFO info{};
info.DeleteFile = FALSE;
return SetFileInformationByHandle(hfile,
FileDispositionInfo, &info, sizeof(info));Author
Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.
需要完整排版与评论请前往来源站点阅读。