Why does CreateFile return invalid handle?

我们两清 提交于 2019-12-13 04:33:33

问题


I have CreateFile() to create a hidden file type but the problem that it keeps returning invalid handle.

file = CreateFileW(_T("hey.txt"),
                   GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
                   0, 0);
error = GetLastError();
WriteFile(file, buff, sizeof(buff),
          &dwRet, NULL);

Any idea?


回答1:


It would probably be best if you showed the exact code that you're using including all the error checking, and how you do it, is important (especially in the case of this question)...

The correct error checking for your code should be something more like...

file = CreateFile(_T("hey.txt"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);

if (file == INVALID_HANDLE_VALUE)
{
   const DWORD error = GetLastError();

   // Do something!
}
else
{  
   if (!WriteFile(file, buff, sizeof(buff), &dwRet, NULL))
   {
      const DWORD error = GetLastError();

      // Do something!
   }
}

You should only be checking for an error if you get a return value of INVALID_FILE_HANDLE as CreateFile() might not reset the last error before it starts and so you might get spurious error values from GetLastError() if the function succeeds...

A last error of 6, ERROR_INVALID_HANDLE, is unusual from CreateFile() unless you're using the template file parameter, which you're not...

Your code using CreateFileW and _T("") is incorrect and wont compile in a non unicode build. Better to use CreateFile and _T("") or CreateFileW and L"".

Your code will not create a hidden file, see molbdnilo's answer.




回答2:


0 is not a valid parameter for dwFlagsAndAttributes. To create a hidden file, pass FILE_ATTRIBUTE_HIDDEN.




回答3:


If "C:\test.txt" exists and is hidden, then following code fails (h = INVALID_HANDLE_VALUE) :

h = CreateFile("C:\\test.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);

this fails too (argument 6 == FILE_ATTRIBUTES_NORMAL or argument6 == 0 seems so be the same) :

h = CreateFile("C:\\test.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

but this works :

h = CreateFile("C:\\test.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_HIDDEN, 0);

So roughly in other words : if the file already exists and is hidden then CreateFile with "CREATE_ALWAYS" fails if argument 6 != FILE_ATTRIBUTE_HIDDEN.



来源:https://stackoverflow.com/questions/5926087/why-does-createfile-return-invalid-handle

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