Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

c++ - Why does CreateFile return invalid handle?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...