2013-05-01 2 views
2

stat()를 사용하여 폴더에 포함 된 모든 파일을 나열하려고합니다. 그러나이 폴더에는 다른 폴더도 들어 있으며 그 내용도 표시하려고합니다. stat()가 폴더를 파일과 구별 할 수 없기 때문에 내 재귀가 무한대가됩니다. 사실 모든 파일은 폴더로 나열됩니다. 어떤 충고? man 2 stat에서stat()로 파일과 디렉토리를 구분할 수 없습니다.

using namespace std; 

bool analysis(const char dirn[],ofstream& outfile) 
{ 
cout<<"New analysis;"<<endl; 
struct stat s; 
struct dirent *drnt = NULL; 
DIR *dir=NULL; 

dir=opendir(dirn); 
while(drnt = readdir(dir)){ 
    stat(drnt->d_name,&s); 
    if(s.st_mode&S_IFDIR){ 
     if(analysis(drnt->d_name,outfile)) 
     { 
      cout<<"Entered directory;"<<endl; 
     } 
    } 
    if(s.st_mode&S_IFREG){ 
     cout<<"Entered file;"<<endl; 
    } 

} 
return 1; 
} 

int main() 
{ 
    ofstream outfile("text.txt"); 
    cout<<"Process started;"<<endl; 
    if(analysis("UROP",outfile)) 
     cout<<"Process terminated;"<<endl; 
    return 0; 
} 

답변

2

내가 생각하는 당신의 오류가 뭔가 다른 . 각 디렉토리 목록에는 두 개의 '의사 디렉토리'(공식 용어가 무엇인지 모름)가 포함되어 있습니다. 현재 디렉토리 및 '..'상위 디렉토리.

코드가 이러한 디렉토리를 따라 가며 무한 루프가 발생합니다. 이 의사 디렉토리를 제외하려면 코드를 이와 같이 변경해야합니다.

if (s.st_mode&S_IFDIR && 
    strcmp(drnt->d_name, ".") != 0 && 
    strcmp(drnt->d_name, "..") != 0) 
{ 
    if (analysis(drnt->d_name,outfile)) 
    { 
     cout<<"Entered directory;"<<endl; 
    } 
} 
+0

존이 말했듯이 나는 무한 재귀를 막을 수 있었다. 고맙습니다! 그러나 여전히 일반 파일과 폴더를 구별 할 수는 없습니다 ... – PptSbzzgt

1

:

은 다음 POSIX 매크로는 된 st_mode 필드를 사용하여 파일 형식을 확인하기 위해 정의

:

 S_ISREG(m) is it a regular file? 

     S_ISDIR(m) directory? 
관련 문제