Question

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)?

Was it helpful?

Solution

If you only want write access, then you may as well only specify GENERIC_WRITE.

Since you specify that you want exclusive access, that call will fail if there is another handle to the file open. You say that the function call is succeeding when another handle exists with FILE_SHARE_READ share mode. But you are mistaken. In that scenario, the call to CreateFile in your question fails.


According to the comments it sounds like you want to have the file open for exclusive access, concurrent with other parties having the file open. That is not possible. Exclusive means to the exclusion of all others. When you have a file open exclusively that means that yours is the one and only open handle to that file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top