温馨提示×

ubuntu readdir如何过滤

小樊
38
2026-10-24 05:01:41
栏目: 智能运维

在 Ubuntu(Linux)下使用 readdir 读取目录时,过滤通常有两种做法:

  1. 读取所有条目,然后在代码里过滤
  2. 结合 opendir + 自定义逻辑过滤(如按名称、类型)

下面用 C 语言 示例说明(这是 readdir 的标准用法)。


一、基础 readdir 用法

#include <stdio.h>
#include <dirent.h>

int main() {
    DIR *dir = opendir(".");
    struct dirent *entry;

    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

二、按文件名过滤(最常见)

示例:只显示 .txt 文件

#include <stdio.h>
#include <string.h>
#include <dirent.h>

int main() {
    DIR *dir = opendir(".");
    struct dirent *entry;

    while ((entry = readdir(dir)) != NULL) {
        if (strstr(entry->d_name, ".txt")) {
            printf("%s\n", entry->d_name);
        }
    }

    closedir(dir);
    return 0;
}

三、过滤 . 和 ..

if (strcmp(entry->d_name, ".") == 0 ||
    strcmp(entry->d_name, "..") == 0)
    continue;

四、按文件类型过滤(推荐)

readdir 返回的 d_type 可用于类型判断(Linux 支持):

if (entry->d_type == DT_REG)  // 普通文件
if (entry->d_type == DT_DIR)  // 目录

示例:只列出目录

while ((entry = readdir(dir)) != NULL) {
    if (entry->d_type == DT_DIR) {
        printf("[DIR] %s\n", entry->d_name);
    }
}

⚠️ 如果 d_type == DT_UNKNOWN,需要用 stat() 进一步判断


五、更严格的类型过滤(stat 方式)

#include <sys/stat.h>

struct stat st;
stat(entry->d_name, &st);

if (S_ISREG(st.st_mode)) {
    // 普通文件
}

六、Shell 层面过滤(非 C)

如果你只是想用命令过滤:

ls *.txt

或

find . -maxdepth 1 -name "*.txt"

七、常见过滤场景总结

需求 方法
按后缀 strstr / strcmp
隐藏文件 d_name[0] == '.'
目录 d_type == DT_DIR
普通文件 d_type == DT_REG
精确类型 stat()

如果你是指 C++ / Python / Shell / 某个具体框架 的 readdir,告诉我,我可以给对应示例。

0 踩