温馨提示×

centos readdir如何过滤文件

小樊
42
2026-10-09 01:24:01
栏目: 智能运维

在 CentOS(Linux) 下使用 readdir 读取目录时,readdir 本身并不会过滤文件,它只是逐个返回目录项(struct dirent)。
过滤逻辑需要你在代码里自己实现。

下面分几种常见情况说明。


一、使用 readdir 的基本方式(C 语言)

#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️⃣ 只显示普通文件(排除目录)

if (entry->d_type == DT_REG) {
    printf("%s\n", entry->d_name);
}

常见 d_type:

  • DT_REG:普通文件
  • DT_DIR:目录
  • DT_LNK:符号链接

⚠️ 注意:d_type 在某些文件系统(如 NFS)上可能不可用,需用 stat()。


3️⃣ 使用 stat 精确判断文件类型(推荐)

#include <sys/stat.h>

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

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

4️⃣ 按文件名后缀过滤(如 .log)

if (strstr(entry->d_name, ".log")) {
    printf("%s\n", entry->d_name);
}

或更严谨:

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

5️⃣ 按权限 / 大小过滤

if (st.st_mode & S_IRUSR) {  // 当前用户可读
}

if (st.st_size > 1024) {     // 大于 1KB
}

三、完整示例(过滤普通 .txt 文件)

#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

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

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

        stat(entry->d_name, &st);
        if (S_ISREG(st.st_mode) &&
            strstr(entry->d_name, ".txt")) {
            printf("%s\n", entry->d_name);
        }
    }

    closedir(dir);
    return 0;
}

四、如果你只是想在 Shell 里过滤

ls *.log

或

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

如果你能说明:

  • 用 C / C++ / Shell / Python
  • 按 类型 / 后缀 / 时间 / 大小 过滤

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

0 踩