Umesha MS
Umesha MS

Reputation: 2921

CreateFile() Failed With GetLastError() = 5

I have written a sample application to read the file from the other file. When I run this application form virtual machine I am getting Access denied. Below is the code.

int _tmain(int argc, _TCHAR* argv[])
{
    WCHAR *wcsPath = L"\\\\150.160.130.22\\share\\123.XML";

    HANDLE hFile = CreateFileW(wcsPath,
                               GENERIC_READ,
                               FILE_SHARE_READ,
                               NULL,
                               OPEN_EXISTING,
                               0,
                               0);

    if (NULL == hFile)
    {
        printf("failed - %d", GetLastError());
    }

    return 0;
}

Please let me know any changes.

Upvotes: 1

Views: 32099

Answers (3)

Cheeso
Cheeso

Reputation: 192621

I believe the documentation for CreateFile holds the answer.

It may be that your dwShareMode is causing the problem. Using FILE_SHARE_READ there says, "allow other openers to open the file for READ access". If you do not specify FILE_SHARE_WRITE` , then other openers will not be able to open the file for writing - your call would prevent that.

But, CreateFile, I believe, also fails when the sharemode would be violated by prior openers. If this is true, then if another application already has the file open for write access, then your call to CreateFile will fail, if you specify dwShareMode = FILE_SHARE_READ. Do you see? You may need to specify FILE_SHARE_WRITE | FILE_SHARE_READ for that dwShareMode parameter.

Try it.

Upvotes: 2

Seva Alekseyev
Seva Alekseyev

Reputation: 61388

The error output of CreateFileW() is INVALID_HANDLE_VALUE, not NULL. Now, NULL definitely sounds like a wrong value for a file handle too, but still.

Is the pasted code snippet exactly the content of your program, or a retelling?

EDIT: I see there's a VM involved. Can you open the file in Notepad from the virtual machine where the program is running and erroring out?

Upvotes: 1

Andrey Agibalov
Andrey Agibalov

Reputation: 7694

Error code 5 stands for "Access is Denied". You should check your user's access rights.

Upvotes: 10

Related Questions