How to delete a file open in another program thru c++???

Nov 16, 2013 at 5:28pm
Hi,
im making a small program that deletes a file open in another program?
for example:
if myfile.txt is open in a text editor in read write mode,
then normally windows wont allow me to delete it or move it, right?
so how will I find the name of the text file editors process?
then if I kill it with TerminateProcess() I can safely delete myfile.txt...:)
Is there an easy way of doing this?
Please help:)
Nov 16, 2013 at 7:45pm
closed account (13bSLyTq)
Hi,

You need to perform a global string-handle check, OR check inside all processes if they posses the handle for the specific file Close the handle.
If not do nothing.
Nov 16, 2013 at 8:46pm
How will I check inside all
processes if they possess the handle for
the specific file ?
Please help:)
Nov 17, 2013 at 11:16am
@OrionMaster: help?
@Cplusplusforum: help?
@Disch: help?
@modoran: help?
@DTSCode: help?
Nov 17, 2013 at 4:34pm
It is NOT recommended to close the handle because the 3rd party process will have no way of knowing it and the following problem may occur:

- The handle will be reused by the kernel sooner or later.
- 3rd party process thinks the file is still opened and it will then close something you didn't intend to close. This problem can be very hard to track down because it never reproduces the same way twice.


So you either call TerminateProcess directly or use something like MoveFileEx to automatically delete the file on next reboot. This is the most safely option.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365240%28v=vs.85%29.aspx
Nov 17, 2013 at 5:17pm
@modoran:
how will I know in which program is myfile.txt is opened ?
If i get the path to the exe then i can know the process name and I can kill it with TerminateProcess(), by getting PID of exe!
Please help?
Nov 17, 2013 at 5:46pm
If you know exe name then you can get a snapshot of all running processes and do a string comparison. If you have a match, get the PID and call TerminateProcess.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686701%28v=vs.85%29.aspx
Nov 17, 2013 at 5:50pm
Im asking How will i get the path to exe that is the program in which Myfile.txt is opened?
Nov 17, 2013 at 5:57pm
You have some sample code here. Use it at your own risk !
http://forum.sysinternals.com/howto-enumerate-handles_topic18892.html
Nov 18, 2013 at 1:19pm
I think it is risky, any other way?
Topic archived. No new replies allowed.