温馨提示×

ubuntu readdir怎样过滤

小樊
40
2026-10-06 14:20:44
栏目: 智能运维

在 Ubuntu(Linux)下使用 readdir 读取目录时,readdir 本身不会帮你过滤文件,你需要在拿到 struct dirent 后自己写判断逻辑来过滤。

下面从 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️⃣ 过滤掉 . 和 ..

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

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

2️⃣ 按文件类型过滤(推荐)

使用 entry->d_type:

while ((entry = readdir(dir)) != NULL) {
    if (entry->d_type == DT_REG)      // 普通文件
        printf("FILE: %s\n", entry->d_name);
    else if (entry->d_type == DT_DIR) // 目录
        printf("DIR : %s\n", entry->d_name);
}

常见类型:

  • DT_REG 普通文件
  • DT_DIR 目录
  • DT_LNK 符号链接
  • DT_UNKNOWN 未知(某些文件系统)

⚠️ 注意:d_type 不一定在所有文件系统都可靠


3️⃣ 使用 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("REG FILE: %s\n", entry->d_name);
    else if (S_ISDIR(st.st_mode))
        printf("DIR     : %s\n", entry->d_name);
}

4️⃣ 按后缀名过滤(如 .txt)

#include <string.h>

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

或:

char *dot = strrchr(entry->d_name, '.');
if (dot && strcmp(dot, ".txt") == 0)
    printf("%s\n", entry->d_name);

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

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

三、进阶:使用 scandir 自动过滤(更方便)

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

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

自定义过滤函数:

int filter(const struct dirent *e) {
    return strcmp(e->d_name, ".") && strcmp(e->d_name, "..");
}

四、总结

需求 方法
排除 . .. 字符串判断
判断文件/目录 d_type 或 stat
后缀过滤 strstr
隐藏文件 d_name[0] == '.'
自动过滤 scandir

如果你有 具体过滤条件(比如“只要 .log 文件”“排除软链接”),我可以给你完整示例。

0 踩