温馨提示×

debian copendir如何过滤文件

小樊
46
2026-10-04 00:21:11
栏目: 智能运维

在 Debian(或者说在 C 语言环境下,因为 opendir 是 POSIX 的目录操作函数)里,opendir 本身不能过滤文件,它只是打开目录,返回 DIR *。
真正“过滤”是在 readdir 循环中做判断。

下面给你几种常见做法。


一、最基础:opendir + readdir 手动过滤

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

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

    if (!dir) {
        perror("opendir");
        return 1;
    }

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

        // 只显示 .txt 文件
        if (strstr(entry->d_name, ".txt"))
            printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

✅ 适合:

  • 简单后缀过滤
  • 文件名包含/匹配规则

二、按文件类型过滤(普通文件 / 目录)

readdir 只给名字,类型不可靠,需用 stat

#include <sys/stat.h>

struct stat st;
char path[256];

while ((entry = readdir(dir)) != NULL) {
    snprintf(path, sizeof(path), "./%s", entry->d_name);
    stat(path, &st);

    if (S_ISREG(st.st_mode))      // 普通文件
        printf("FILE: %s\n", entry->d_name);
    else if (S_ISDIR(st.st_mode)) // 目录
        printf("DIR : %s\n", entry->d_name);
}

三、使用 scandir(最推荐,自带过滤)

scandir 可以直接传 过滤函数

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

int filter(const struct dirent *e) {
    return strncmp(e->d_name, "test", 4) == 0;
}

int main() {
    struct dirent **namelist;
    int n = scandir(".", &namelist, filter, alphasort);

    for (int i = 0; i < n; i++) {
        printf("%s\n", namelist[i]->d_name);
        free(namelist[i]);
    }
    free(namelist);
}

✅ 优点:

  • 代码简洁
  • 自动排序
  • 不用手动跳过 . / ..

四、正则表达式过滤(高级)

#include <regex.h>

int filter(const struct dirent *e) {
    regex_t reg;
    regcomp(&reg, ".*\\.log$", REG_EXTENDED);
    int ret = regexec(&reg, e->d_name, 0, NULL, 0);
    regfree(&reg);
    return ret == 0;
}

五、如果你只是用 shell 而不是 C

ls *.txt

或

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

总结

方法 是否推荐 说明
opendir + readdir ✅ 基础用法
stat 判断类型 ✅ 精确控制
scandir ⭐⭐⭐ 最方便
正则 ⭐⭐ 复杂规则

如果你能告诉我:

  • 是 C 程序 还是 shell
  • 想按 后缀 / 类型 / 权限 / 时间 过滤

我可以直接给你完整可用代码。

0 踩