如何在linux C中枚举目录条目时忽略子目录

时间:2016-10-30 13:17:56

标签: c linux console

我必须忽略属于子目录的条目。怎么办?我想我必须使用public synchronized void sync_method() { //code snippet B } ,但我不知道如何。你能帮我吗?

这是我的代码:

S_ISDIR(s.st_mode)

1 个答案:

答案 0 :(得分:1)

如果系统支持,您可以使用d_type获取文件类型:

if (ent->d_type == DT_DIR) {
     /* ent->d_name is a directory. */
}

否则,您可以按如下方式使用stat(2)

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

...

char buf[4096];
snprintf(buf, sizeof buf, "%s/%s", dir_name, ent->d_name);
struct stat sb;

if (stat(buf, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    /* d_name is a directory. */
}