温馨提示×

ubuntu readdir怎么过滤文件

小樊
42
2026-10-15 09:33:53
栏目: 智能运维

在 Ubuntu(Linux)下使用 readdir 过滤文件,通常是指 在 C/C++ 程序里使用 readdir() 读取目录时,按条件过滤文件名。下面按常见场景说明。


一、readdir 基本用法

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

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

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

    closedir(dir);
    return 0;
}

二、常见过滤方式

1️⃣ 过滤掉 . 和 ..

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

2️⃣ 按文件后缀过滤(如 .txt)

#include <string.h>

if (strstr(entry->d_name, ".txt") == NULL)
    continue;

或严格判断后缀:

size_t len = strlen(entry->d_name);
if (len < 4 || strcmp(entry->d_name + len - 4, ".txt") != 0)
    continue;

3️⃣ 按文件类型过滤(普通文件 / 目录)

readdir 本身只给名字,要准确判断需要用 stat:

#include <sys/stat.h>

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

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

✅ 推荐用 fstatat 更安全(避免竞争)


4️⃣ 使用 fnmatch 做通配符过滤

#include <fnmatch.h>

if (fnmatch("*.log", entry->d_name, 0) == 0) {
    // 匹配 *.log
}

5️⃣ 隐藏文件过滤(以 . 开头)

if (entry->d_name[0] == '.')
    continue;

三、完整示例:只列出普通 .txt 文件

DIR *dir = opendir(".");
struct dirent *e;
struct stat st;

while ((e = readdir(dir))) {
    if (e->d_name[0] == '.') continue;

    char path[256];
    snprintf(path, sizeof(path), "./%s", e->d_name);
    stat(path, &st);

    if (S_ISREG(st.st_mode) &&
        strstr(e->d_name, ".txt"))
        printf("%s\n", e->d_name);
}
closedir(dir);

四、如果你不是写 C 程序

Shell 中(不用 readdir)

ls *.txt

Python

import os
[f for f in os.listdir('.') if f.endswith('.txt')]

如果你能说明:

  • 用 C / C++ / Shell / Python
  • 想按 后缀 / 类型 / 权限 / 时间 过滤

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

0 踩