2013-05-01 37 views
2

我想列出使用stat()文件夾中包含的所有文件。但是,該文件夾還包含其他文件夾,其內容也要顯示。我的遞歸變得無限,因爲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

按照John的說法,我設法阻止了無限遞歸。謝謝!但是,它仍然無法區分文件夾中的常規文件... – PptSbzzgt 2013-05-02 07:30:33

1

man 2 stat

以下POSIX宏定義使用 的 ST_MODE現場檢查文件類型:

 S_ISREG(m) is it a regular file? 

     S_ISDIR(m) directory?