I need to check for exclusive write access of a file. I put in this code.
HANDLE fileH = CreateFile(filePath,
GENERIC_READ | GENERIC_WRITE,
0, // For Exclusive access
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (fileH != INVALID_HANDLE_VALUE) {
// We have exclusive write access.
CloseHandle(fileH);
}
else {
// No exclusive write access.
}
Even for files which are open in shared read mode somewhere else, this is resulting in files getting opened. Though this is the result I wanted, but is this behavior of CreateFile API correct? Or should I only specify GENERIC_WRITE, instead of (GENERIC_READ | GENERIC_WRITE)?
INVALID_HANDLE_VALUE
means that theCreateFile
operation failed. If you are checking for exclusive write access, you should test for:INVALID_HANDLE_VALUE
andGetLastError() == ERROR_SHARING_VIOLATION
. Otherwise the sample code could generate a false positive. – Pressacco