2010-05-15 43 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