温馨提示×

debian readdir怎样过滤

小樊
52
2026-10-04 09:21:32
栏目: 智能运维

在 Debian(或任意 Linux)下,readdir 一般指的是 readdir() / readdir_r() 这类 C 库函数(<dirent.h>)。它本身不会过滤,只能逐个读取目录项,过滤需要在代码里自己做。

下面按常见场景说明。


一、使用 readdir 手动过滤(最常用)

基本示例(C 语言)

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

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

    while ((entry = readdir(dir)) != NULL) {
        // 过滤掉 . 和 ..
        if (strcmp(entry->d_name, ".") == 0 ||
            strcmp(entry->d_name, "..") == 0)
            continue;

        // 只显示普通文件
        if (entry->d_type == DT_REG)
            printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

二、常见过滤方式

1️⃣ 按文件名过滤

// 只显示 .txt 文件
if (strstr(entry->d_name, ".txt") == NULL)
    continue;

2️⃣ 按文件类型过滤

DT_REG   // 普通文件
DT_DIR   // 目录
DT_LNK   // 符号链接

⚠️ 注意:d_type 在某些文件系统上可能是 DT_UNKNOWN


3️⃣ 结合 stat 精确判断

#include <sys/stat.h>

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

if (S_ISDIR(st.st_mode)) {
    // 目录
}

三、在 Shell 中“过滤 readdir 的效果”

如果你不是写 C,而是想像 readdir 一样列目录并过滤:

ls -1 | grep '\.txt$'

或:

find . -maxdepth 1 -type f

四、使用 scandir(更方便)

scandir 支持过滤函数 + 自动排序:

int filter(const struct dirent *e) {
    return strncmp(e->d_name, ".", 1) != 0;
}
struct dirent **list;
int n = scandir(".", &list, filter, alphasort);

五、总结

方式 是否过滤 说明
readdir ❌ 需手动过滤
scandir ✅ 支持 filter 函数
shell ✅ 最方便

如果你能说明:

  • 是 C / C++ / Python / Shell
  • 想按 文件名 / 类型 / 权限 / 时间 过滤

我可以给你更精确的示例。

0 踩