How do I delete a file that is locked?

I am writing a Windows desktop application in C ++ MFC.

The application creates an index file and writes the information over and over.

If the app crashes, the next time the app starts, it will delete the split index file and create a new one. I think that in some cases the index file will be locked. It will be a disaster if I cannot delete the locked index file.

How can I ensure that I can delete the file and create a new one? I can make sure that no other application will open the index file. It cannot be removed just because the application crashed.

Can anyone please help?

+2


source to share


5 answers


If there is no process in which the file is open, it cannot remain locked. You may find that as long as your broken process actually dies (rather than hangs), you have no problem.



If you really need to be sure that you can delete a file from one process while another process is open, you need both processes to open it with a flag FILE_SHARE_DELETE

.

+7


source


To unlock a file, you must close all associated handles. The best way to do this is to terminate the crashed application that is still running (and owns the file descriptor).



To find the crashed application, you can use the technique described in this article. This is what Process Explorer does when it searches for file descriptors with the specified name.

+3


source


Most likely the answer is "you cannot delete the locked file". OS won't let you.

Instead, I would work on it with something like this.

  • Check the existing index files, remove them if there are no locks.
  • Create a new index file, if the first "name" is met, check index01, etc. until you find one that is not in use, then use it as your index file for this program run.
  • On normal exit, clear the index file.

Bonus Credit: Allows users to "repair" a broken index file rather than automatically deleting them.

0


source


Sometimes you can rename a locked file. You should probably fix the real problem, not the symptom.

0


source


I can recommend this tool: http://lockhunter.com/download.htm

This helped me unlock my Skype account on Windows 8 by deleting "% appdata% / Skype / my-user-profile" while other tools and procedures did not help in my case (link to "other skype" instance may exist "which also bites many other users.)

0


source







All Articles