2012-02-15 4 views
6

이 코드는 디렉토리를 열고 목록이 일반 파일 (폴더라는 의미)이 아닌지 확인합니다. 어떻게하면 C++로 파일과 폴더를 구별 할 수 있습니까? 이 도움이된다면 여기 내 코드입니다 :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

사용'stat' (또는'lstat') 다른 경우 당신은 원래 디렉토리와 파일 이름을 패치해야 할 것 및 'S_ISDIR'. –

답변

7

한 가지 방법은 다음과 같습니다

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

당신은 GNU C Library Manualstruct dirent 문서를 볼 수 있습니다.

1

완성도를 들어, 다른 방법은 다음과 같습니다

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; 

.

관련 문제