The CreateFile function has a flag called FILE_, 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 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_, 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));
I don’t mean to nitpick, but I wonder if this approach could potentially cause issues in the future.
`FILE_DISPOSITION_INFO` doesn’t imply that `DeleteFile` will always be its only field. While that’s true today, additional fields could be added in future versions.
If that happens, these helper methods would initialize a new `FILE_DISPOSITION_INFO` and set only `DeleteFile`, which might unintentionally overwrite any future fields with their default values.
Am I right?
The call includes both a pointer to the structure (&info) and its size (sizeof(info)). The structure’s size allows to say which version is passed. In the case new fields are added to FILE_DISPOSITION_INFO, existing programs will pass 4 as the struct size parameter, but new programs will pass the bigger size of the updated structure.
This is a common pattern in Win16/32/64. Sometimes size gets its own parameter, sometimes it’s registered as the first field of the structure (info.size = sizeof(info)).
Another option of course is to never close the last handle, and display an icon on the screen forever: “warning, do not turn off power”.
***just kidding***
I use this trick by setting that disposition as soon as I open the file and only clearing it once the file has been written successfully, so if the process crashes or is terminated there won’t be any lingering partially-written files.