Skip to content
TopicTracker
From devblogs.microsoft.com/oldnewthingView original
TranslationTranslation

I opened a file with FILE_FLAG_DELETE_ON_CLOSE, but now I changed my mind

Once a file is opened with FILE_FLAG_DELETE_ON_CLOSE, the deletion cannot be undone. However, an alternative approach can achieve a similar result without the irreversible flag.

Background

Raymond Chen's "The Old New Thing" is a long-running Microsoft developer blog that explains Windows internals and Win32 API quirks, often with historical context. This post addresses a specific Windows file-handling flag: `FILE_FLAG_DELETE_ON_CLOSE`, which tells the OS to automatically delete a file when all handles to it are closed. Once you set this flag when opening a file, Windows provides no way to *unset* it on that same handle — the deletion is irrevocably scheduled. Chen explains the (somewhat obscure) workaround: open a second handle to the same file *without* the flag, then close the first handle; because the second handle still exists, the file won't be deleted, effectively "canceling" the pending deletion. This is a classic example of Windows API design where a flag acts as a one-way commitment, and the solution relies on the OS's reference-counting behavior for file objects.

Related stories

  • The article describes a project to create a hybrid barcode that combines a traditional 1D UPC barcode with a 2D QR code, allowing scanners to read the numeric code up close while QR readers can decode the full pattern from a distance.