2010-05-15 41 views
0

我正在對目錄中的所有文件進行簡單測試。 但是由於某種原因,有時候,他們的行爲是錯誤的? 我的代碼有什麼不好?測試目錄S_ISDIR行爲不一致

using namespace std; 

int main() { 
string s = "/home/"; 
    struct dirent *file; 
    DIR *dir = opendir(s.c_str()); 

    while ((file = readdir(dir)) != NULL){ 
    struct stat * file_info = new (struct stat); 

    stat(file->d_name,file_info); 
    if ((file_info->st_mode & S_IFMT) == S_IFDIR) 
    cout << "dir" << endl; 
    else 
    cout << "other" << endl; 
    } 
    closedir(dir); 
} 
+1

請解釋您的意思是「行爲錯誤」。是否有目錄輸出爲「other」,或其他輸出爲「dir」的東西? – 2010-05-15 20:32:18

+0

@Roland Illig:都 – coubeatczech 2010-05-15 22:46:35

回答

4

你犯了一些錯誤,最重要的是撥打stat()而不檢查其返回值。我修改你的程序是:

#include <cstdio> 
#include <dirent.h> 
#include <iostream> 
#include <string> 
#include <sys/stat.h> 

using namespace std; 

int main() { 
    string s = "/home/"; 
    struct dirent *file; 
    DIR *dir = opendir(s.c_str()); 

    while ((file = readdir(dir)) != NULL) { 
    struct stat file_info; 

    if (stat(file->d_name, &file_info) == -1) { 
     perror("stat"); 
     return 1; 
    } 

    if (S_ISDIR(file_info.st_mode)) 
     cout << "dir " << file->d_name << endl; 
    else 
     cout << "other " << file->d_name << endl; 
    } 
    closedir(dir); 
} 

當我跑了,我得到了這樣的輸出:

$ ./a.exe 
dir . 
dir .. 
stat: No such file or directory 

現在我看到stat被稱爲與roland文件名,不存在中我目前的工作目錄。您必須在文件名前添加目錄名稱。

你的第二個錯誤是每次分配一個新的struct stat但使用後沒有釋放內存。默認情況下,C++沒有垃圾收集,所以你的程序很快就會耗盡內存。

0

如果只S_IFDIR設爲您可以嘗試檢查:

if((statbuf.st_mode & S_IFDIR) == S_IFDIR) 
{//dir 
} 

我看到了以下定義:

#define _S_IFMT   0xF000   /* file type mask */ 
#define _S_IFDIR  0x4000   /* directory */ 
#define _S_IFCHR  0x2000   /* character special */ 
#define _S_IFIFO  0x1000   /* pipe */ 
#define _S_IFREG  0x8000   /* regular */ 
#define _S_IREAD  0x0100   /* read permission, owner */ 
#define _S_IWRITE  0x0080   /* write permission, owner */ 
#define _S_IEXEC  0x0040   /* execute/search permission, owner */ 

我不知道你的情況,但無論是S_IFDIR不設置掩碼0xF000內的一個或多於一個位。

+0

我認爲((file_info-> st_mode&S_IFMT)== S_IFDIR)是正確的。 – Artefacto 2010-05-15 20:18:59