2012-02-15 58 views
6

Tôi có mã này mở thư mục và kiểm tra xem danh sách không phải là tệp thông thường (có nghĩa là nó là một thư mục) nó cũng sẽ mở nó. Làm thế nào tôi có thể phân biệt giữa các tập tin và thư mục với C + +. đây là mã của tôi nếu điều này giúp:Phân biệt giữa các thư mục và tệp trong C++

#include <sys/stat.h> 
#include <cstdlib> 
#include <iostream> 
#include <dirent.h> 
using namespace std; 

int main(int argc, char** argv) { 

// Pointer to a directory 
DIR *pdir = NULL; 
pdir = opendir("."); 

struct dirent *pent = NULL; 

if(pdir == NULL){ 
    cout<<" pdir wasn't initialized properly!"; 
    exit(8); 
} 

while (pent = readdir(pdir)){ // While there is still something to read 
    if(pent == NULL){ 
    cout<<" pdir wasn't initialized properly!"; 
    exit(8); 
} 

    cout<< pent->d_name << endl; 
} 

return 0; 

}

+0

Sử dụng 'stat' (hoặc 'lstat') và 'S_ISDIR'. –

Trả lời

7

Một cách sẽ là:

switch (pent->d_type) { 
    case DT_REG: 
     // Regular file 
     break; 
    case DT_DIR: 
     // Directory 
     break; 
    default: 
     // Unhandled by this example 
} 

Bạn có thể xem tài liệu struct dirent trên GNU C Library Manual.

1

Để hoàn chỉnh, một cách khác sẽ là:

struct stat pent_stat; 
    if (stat(pent->d_name, &pent_stat)) { 
     perror(argv[0]); 
     exit(8); 
    } 
    const char *type = "special"; 
    if (pent_stat.st_mode & _S_IFREG) 
     type = "regular"; 
    if (pent_stat.st_mode & _S_IFDIR) 
     type = "a directory"; 
    cout << pent->d_name << " is " << type << endl; 

Bạn sẽ phải vá các tên tập tin với các thư mục gốc nếu nó khác với .

Các vấn đề liên quan