2011-11-22 2 views

risposta

58

beh, eravamo tutti n0obs ad un certo punto nel tempo. Nessun problema nel chiedere. Ecco una semplice funzione che fa esattamente questo:

#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()' restituisce 'INVALID_FILE_ATTRIBUTES' quando si verifica un errore. Devi usare 'GetLastError()' per scoprire cosa sia effettivamente questo errore. Se restituisce 'ERROR_PATH_NOT_FOUND',' ERROR_FILE_NOT_FOUND', 'ERROR_INVALID_NAME' o' ERROR_BAD_NETPATH', in realtà non esiste. Ma se restituisce la maggior parte degli altri errori, allora qualcosa esiste effettivamente nel percorso specificato ma gli attributi semplicemente non sono accessibili. –

+3

Per quelli che inciampano in questa risposta, tieni presente che il codice sopra riportato è ANSI non Unicode. Per Unicode moderno, è meglio prendere un parametro LPCTSTR come lo snippet in questa altra risposta StackOverflow: http://stackoverflow.com/a/6218445. (LPCTSTR sarà tradotto in 'wchar_t *' dal compilatore.). È quindi possibile racchiudere la funzione che riconosce Unicode per prendere uno 'std :: wstring 'in C++ anziché' std :: string'. – JasDev

4

0,1 seconda ricerca Google:

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

Questo codice potrebbe funzionare:

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