2011-11-22 42 views

回答

58

好吧,我們都在n0obs在某個時間點。詢問沒問題。下面是一個簡單的函數,它正是這樣做的:

#include <windows.h> 
#include <string> 

bool dirExists(const std::string& dirName_in) 
{ 
    DWORD ftyp = GetFileAttributesA(dirName_in.c_str()); 
    if (ftyp == INVALID_FILE_ATTRIBUTES) 
    return false; //something is wrong with your path! 

    if (ftyp & FILE_ATTRIBUTE_DIRECTORY) 
    return true; // this is a directory! 

    return false; // this is not a directory! 
} 
+7

'GetFileAttributes()'在發生故障時返回'INVALID_FILE_ATTRIBUTES'。你必須使用'GetLastError()'來查明實際上的失敗。如果它返回'ERROR_PATH_NOT_FOUND','ERROR_FILE_NOT_FOUND','ERROR_INVALID_NAME'或'ERROR_BAD_NETPATH',那麼它確實不存在。但是,如果它返回大多數其他錯誤,那麼實際上在指定的路徑上存在某些內容,但這些屬性根本無法訪問。 –

+3

對於那些在這個答案的絆腳石,請記住,上面的代碼是ANSI而不是Unicode。對於現代的Unicode,最好在這個其他的stackoverflow答案中使用LPCTSTR參數,如片段:http://stackoverflow.com/a/6218445。 (LPCTSTR將被編譯器轉換爲'wchar_t *')。然後,您可以將該識別Unicode的函數包裝成一個C++'std :: wstring'而不是'std :: string'。 – JasDev

4

0.1秒谷歌搜索:

BOOL DirectoryExists(const char* dirName) { 
    DWORD attribs = ::GetFileAttributesA(dirName); 
    if (attribs == INVALID_FILE_ATTRIBUTES) { 
    return false; 
    } 
    return (attribs & FILE_ATTRIBUTE_DIRECTORY); 
} 
6

此代碼可能工作:如果鏈接到外殼輕量級API

//if the directory exists 
DWORD dwAttr = GetFileAttributes(str); 
if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 
相關問題