Min Mun Min Mun - 2 months ago 4x
C++ Question

How to share file detele privilege when I opening a file by ifstream

I want to make the file that can be delete when it was opened by


I know it is easy when using Windows API:


But when I test with opening a file by ifstream.

It can't be deleted when I opening it.

I didn't find any document about setting attribute such like

How should I do to solve this problem?


File permissions differ by operating system:

Whole-file access-sharing for read, write, or delete

write+execute permission on the parent directory. The permissions of the file itself are irrelevant

Since Windows is really the only system with delete access, and it already provides it's own accessor in the form of CreateFile with FILE_SHARE_DELETE, there really isn't a motivation to standardize this functionality.

If this functionality is pivotal to your program you could implement this cross-platform function (note that depending upon file size this could be very expensive):

  1. Open file for read and write with an fstream; if this fails something else has a lock on the file and it would not be possible to open it for delete
  2. Slurp the file
  3. close the file
  4. remove the file; if this fails you do not have delete permissions on the file
  5. Reopen the file for writing with an ofstream
  6. "Unslurp" the file into the ofstream
  7. Return the ofstream

As long as the returned ofstream is open the operating system is responsible for preventing changes to the permissions on the file or it's containing directories. So by virtue of the fact that you have already deleted the file you know that you can still delete the file upon closing the ofstream.