Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if file is open in C++

Tags:

c++

windows

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.

like image 588
AlexandraC Avatar asked Jan 21 '14 12:01

AlexandraC


1 Answers

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.")

like image 120
hmjd Avatar answered Sep 29 '22 21:09

hmjd