温馨提示×

debian copendir如何排除文件

小樊
38
2026-09-28 04:39:43
栏目: 智能运维

在 Debian(或者说 Linux 下 C 语言编程)里,opendir() + readdir() 本身不能“排除文件”,它只会把目录里的所有条目读出来。
所谓“排除文件”,通常是在 读取过程中或之后进行过滤。

下面给你几种常见做法,从简单到规范。


一、最常用:readdir 后手动排除(推荐)

#include <dirent.h>
#include <string.h>
#include <stdio.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 (strcmp(entry->d_name, "test.txt") == 0)
            continue;

        // 排除某种后缀
        if (strstr(entry->d_name, ".log"))
            continue;

        printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

✅ 优点:简单、可控
❌ 缺点:逻辑写在代码里


二、使用 fnmatch 做模式排除(更灵活)

#include <fnmatch.h>

if (fnmatch("*.tmp", entry->d_name, 0) == 0)
    continue;

适合:

  • *.log
  • file_*
  • *.bak

三、使用 scandir(一次性过滤,更干净)

scandir 可以传入 过滤函数:

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

int filter(const struct dirent *d) {
    if (strcmp(d->d_name, ".") == 0 ||
        strcmp(d->d_name, "..") == 0)
        return 0;

    if (strstr(d->d_name, ".log"))
        return 0;

    return 1;
}

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);
}

✅ 推荐用于“列出并排除”


四、如果你想“真正跳过某些文件不打开”

如果你是指:

遍历目录但跳过某些文件不处理

那就 只跳过,不 open():

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

int fd = open(entry->d_name, O_RDONLY);

五、如果你说的不是 C 语言(shell)

如果你其实是想问 Debian 命令行 怎么排除:

ls -I "*.log"

或

find . -type f ! -name "*.log"

总结

场景 方法
C 程序遍历目录 readdir + if 排除
模式匹配 fnmatch
一次性列出 scandir
命令行 ls -I / find

如果你能说清楚:

  • 是 C 程序 还是 shell
  • 想排除的是 文件名 / 后缀 / 类型

我可以给你更精确的代码。

0 踩