CreateFile() Failed With GetLastError() = 5

我们两清 提交于 2021-02-10 20:34:14

问题


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.


回答1:


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




回答2:


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?




回答3:


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.



来源:https://stackoverflow.com/questions/7193348/createfile-failed-with-getlasterror-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!