Reputation: 157
I have to open a handle for a file, before opening the file I need to check whether the file is already opened by another entity. I read CREATE_NEW parameter fails to open the file if already exist. I am opening the file using the api and parameters CreateFile(file_name, GENERIC_WRITE | GENERIC_READ, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
Another entity already opened the file, but when I try to open the same file by calling the above api it returns a proper handle and even the getLastError() returns SUCCESS. But expectation is FAILURE should be returned.
Upvotes: 0
Views: 2334
Reputation: 612934
Your code is already correct. You are passing 0
as the share mode which opens the file with exclusive access. No other party can open the file while that handle lives.
The documentation says this about exclusive share mode:
Prevents other processes from opening a file or device if they request delete, read, or write access.
The logical conclusion from all of this is that you are mistaken in your belief that another party has the file open when you call CreateFile
. If what you report in the question is correct, that cannot be true.
Upvotes: 4
Reputation: 172418
You can try to open your file in exclusive mode. If you are able to do that then it means it is not being used by another process else it is being used.
CreateFile(file_name, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
The dwShareMode which when set to 0 will mean that it is exclusive access. MSDN says:
If this parameter is zero and CreateFile succeeds, the file or device cannot be shared and cannot be opened again until the handle to the file or device is closed.
Upvotes: 2