温馨提示×

centos readdir怎样过滤

小樊
45
2026-09-27 07:59:01
栏目: 智能运维

在 CentOS(或者说 Linux 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️⃣ 按文件类型过滤(目录 / 普通文件)

#include <sys/stat.h>

while ((entry = readdir(dir)) != NULL) {
    struct stat st;
    stat(entry->d_name, &st);

    if (S_ISDIR(st.st_mode))
        printf("[DIR] %s\n", entry->d_name);
    else if (S_ISREG(st.st_mode))
        printf("[FILE] %s\n", entry->d_name);
}

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

#include <string.h>

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

4️⃣ 按前缀过滤

if (strncmp(entry->d_name, "log", 3) == 0)
    printf("%s\n", entry->d_name);

三、更高级:用 scandir(自带过滤函数)

scandir 可以直接传过滤函数:

int filter(const struct dirent *e) {
    return strncmp(e->d_name, "test", 4) == 0;
}

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

四、如果只是 shell 用(非 C)

ls | grep txt

如果你能说清楚:

  • 用 C / C++ / shell
  • 过滤 类型 / 后缀 / 权限 / 时间

我可以直接给你一段可编译的代码。

0 踩