2012-04-06 67 views
2

我有一個用於創建目錄的函數。它採用CreateDirectoryA()CreateDirectory報告如果失敗但錯誤代碼爲ERROR_SUCCESS

CreateDirectory報告說,它失敗了,但是當我檢查使用GetLastError函數(錯誤代碼),它報告ERROR_SUCCESS

代碼:

BOOL isDirCreated = CreateDirectoryA(dirName.c_str(), NULL); 
DWORD dw = GetLastError(); 
if (isDirCreated) { 
     if (!SetFileAttributesA(dirName.c_str(), attributes)) { 
      printf("SetFileAttributes() %s failed with (%d)", dirName.c_str(), GetLastError())); 
      return; 
     } 
    } else { 
     printf("CreateDirectory() %s Failed with (%d)", dirName.c_str(), dw)); 
     if(ERROR_ALREADY_EXISTS != dw) { 
      return; 
     } 
    } 

這將返回:(多次調用函數)

CreateDirectory() testDir Failed with (0) 
CreateDirectory() testDir\dir Failed with (183) 

即使CreateDirectoryA返回false,該目錄也會被創建。首次調用該函數時總會發生失敗。所有後續調用均按預期工作。

CreateDirectory在成功創建目錄時將返回false的任何想法。

下面是一個類似的帖子,但該方案並沒有爲我工作:

ReadFile() says it failed, but the error code is ERROR_SUCCESS

UPDATE 原來這個錯誤造成的,因爲這是在代碼中包含另一頭有一個功能「GetLastError」另一個函數在一個單獨的命名空間中,因此解決方案是按如下方式調用GetLastError。

/* 
* the :: will tell it to use the GetLastError that is available on the global 
* scope. Most of Microsoft's calls don't have any namespace. 
*/ 
DWORD dw = ::GetLastError(); 
+0

您將需要尋找某種類型的DLL,它會被注入到您的進程中並與winapi混淆。病毒掃描程序,這種事情。您可以在VS Output窗口中看到加載的DLL。 – 2012-04-06 15:40:22

+0

如果我明白你在說什麼,你認爲某個DLL正在被加載,並且正在與我的進程混淆,導致它在生成目錄時不正確地報告成功或失敗? – gnash117 2012-04-06 21:21:57

回答

1

原來這個錯誤是因爲所包含的代碼中的其它標題有一個函數「GetLastError函數」的另一功能是在一個單獨的名稱空間,這樣的解決辦法是調用GetLastError如下造成的。

/* 
* the :: will tell it to use the GetLastError that is available on the global 
* scope. Most of Microsoft's calls don't have any namespace. 
*/ 
DWORD dw = ::GetLastError(); 
相關問題