C++ CreateFile() 失败,GetLastError() = 5
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7193348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CreateFile() Failed With GetLastError() = 5
提问by Umesha MS
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.
请让我知道任何变化。
回答by Andrey Agibalov
Error code 5 stands for "Access is Denied". You should check your user's access rights.
错误代码 5 代表“拒绝访问”。您应该检查用户的访问权限。
回答by Seva Alekseyev
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.
CreateFileW() 的错误输出是 INVALID_HANDLE_VALUE,而不是 NULL。现在,对于文件句柄来说,NULL 绝对听起来也是错误的值,但仍然如此。
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?
编辑:我看到涉及到一个虚拟机。您可以从程序正在运行并出错的虚拟机中在记事本中打开该文件吗?
回答by Cheeso
I believe the documentation for CreateFileholds the answer.
我相信CreateFile 的文档包含答案。
It may bethat your dwShareModeis 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.
这可能是你的dwShareMode引起的问题。使用FILE_SHARE_READ
那里说,“允许其他开启者打开文件以进行读取访问”。如果您不指定 FILE_SHARE_WRITE` ,则其他打开程序将无法打开文件进行写入 - 您的调用会阻止这种情况。
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.
但是,我相信,当共享模式被先前的开启者违反时,CreateFile 也会失败。如果这是真的,那么如果另一个应用程序已经打开了该文件以进行写访问,那么您对 CreateFile 的调用将失败,如果您指定 dwShareMode = FILE_SHARE_READ
。你有看到?您可能需要FILE_SHARE_WRITE | FILE_SHARE_READ
为该 dwShareMode 参数指定。
Try it.
尝试一下。