2010-04-16 28 views

回答

1

您可以使用lstatS_ISDIR宏。

E.g.沒有錯誤檢查:

struct stat buffer; 
int status; 
char path[PATH_MAX]; 
DIR *dir = opendir(dir_name); 
... 
struct dirent *de = readdir(dir); 
sprintf(path, "%s/%s", dir_name, de->d_name); 
status = lstat(path, &buffer); 
if(S_ISDIR(buffer.st_mode)) 
{ 
    ... 
} 

編輯:修復包括目錄在lstat路徑(每el.pescado)。正如R Samuel Klatchko所指出的那樣,您可能希望採取白名單方式(S_ISREG),而不是在列入黑名單類型時。

+0

你必須在傳遞路徑到lstat之前結合dirname和filename,例如。做sprintf(路徑,「%s /%s」,dir_name,de-> d_name); – 2010-04-16 22:42:11

+1

只處理常規文件條目('S_ISREG')而不排除目錄條目('S_ISDIR')會更健壯一些。這樣,如果您遇到另一種類型的條目,則不會意外處理它。 – 2010-04-16 22:44:16

+0

剛剛注意到別的東西。你需要考慮是否使用'stat'或'lstat'。如果你有一個符號鏈接到一個真實的文件,你想要處理它還是跳過它?如果你想跳過它,使用'lstat',這樣你就會知道它是一個符號鏈接。如果你不關心它是一個符號鏈接,並且想要處理它,假設它是一個常規文件的符號鏈接,那麼使用'stat'。 – 2010-04-17 06:11:52

0
`void DirectryNFileCount(const char * FileDir) 
{ 
    DIR *dir; 
    int filecount; 
    int dircount; 
    struct dirent *direntry; 
    if ((dir = opendir (FileDir)) == NULL) 
    { 
    /*Error code*/ 
    } 
while((direntry = readdir (dir)) != NULL) 
{ 
if(direntry->d_type==DT_DIR) 
dircount++; 
/*do something with directries  */ 
} 
else 
{ 
    filecount++; 
    std::cout<<"Files Names"<<direntry->d_name<<std::endl; 
} 
} 
    std::cout<<"THIS Directory has "<<filecount<<" FILES and "<<dircount<< " DIRECTORIES"; 
} 
+1

伴隨您的代碼的書面說明會使此答案更有幫助。 – nbryans 2016-11-18 20:56:51