温馨提示×

ubuntu readdir如何过滤文件

小樊
48
2026-09-21 20:43:06
栏目: 智能运维

在 Ubuntu / Linux 下,使用 readdir() 读取目录时,readdir 本身不会过滤文件,它只是逐个返回目录项(struct dirent)。过滤需要在代码中手动判断。

下面从 C 语言(readdir) 和 Shell(ls/find) 两个层面说明。


一、C 语言中使用 readdir 过滤文件

1️⃣ 基本示例(过滤 . 和 ..)

#include <dirent.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;

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

    closedir(dir);
    return 0;
}

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

⚠️ d_type 在某些文件系统上可能不可靠,稳妥做法是用 stat()

用 d_type(快速)

if (entry->d_type == DT_REG)
    printf("普通文件: %s\n", entry->d_name);
if (entry->d_type == DT_DIR)
    printf("目录: %s\n", entry->d_name);

用 stat(可靠)

#include <sys/stat.h>

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

if (S_ISREG(st.st_mode))
    printf("普通文件: %s\n", entry->d_name);

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

#include <string.h>

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

或更严谨:

int len = strlen(entry->d_name);
if (len > 4 && strcmp(entry->d_name + len - 4, ".txt") == 0)
    printf("%s\n", entry->d_name);

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

if (entry->d_name[0] == '.')
    continue; // 跳过隐藏文件

二、Shell 中“过滤 readdir 结果”

虽然 shell 不用 readdir(),但常用等价方式:

1️⃣ ls 过滤

ls *.txt
ls -a        # 含隐藏文件
ls -p | grep -v /

2️⃣ find 过滤

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

3️⃣ 循环(类似 readdir)

for f in *; do
    [ -f "$f" ] && echo "$f"
done

三、常见过滤总结

需求 方法
排除 . .. strcmp
只看普通文件 S_ISREG
只看目录 S_ISDIR
按后缀 strstr
隐藏文件 d_name[0] == '.'

如果你能说明:

  • 用 C / C++ / Python / Shell
  • 想过滤 什么规则(类型 / 后缀 / 权限)

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

0 踩