Is there any way in C++ to detect if a file is already open in another program?.
I want to delete and rewrite some files, but in case a file is opened I want to display an error message. I am using Windows OS.
Taking an action depending on the result of the "is file open query" is a race condition (the query returns false
and then a program opens the file before your program attempts to delete it for example).
Attempt to delete the file using DeleteFile()
and if it fails display the reason the file delete failed, using GetLastError()
. See System Error Codes for the list of error codes (ERROR_SHARING_VIOLATION
which states "The process cannot access the file because it is being used by another process.")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With