温馨提示×

centos readdir如何遍历

小樊
46
2026-09-03 03:00:29
栏目: 智能运维

CentOS(Linux) 下,使用 C 语言 readdir 遍历目录是非常常见的做法。下面给你一个完整、可直接用的示例,并解释关键点。


一、基本思路

  1. 使用 opendir() 打开目录
  2. 使用 readdir() 逐个读取目录项
  3. 使用 closedir() 关闭目录
  4. (可选)递归遍历子目录

二、最简单的 readdir 遍历示例

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

int main(int argc, char *argv[])
{
    DIR *dir;
    struct dirent *entry;

    if (argc < 2) {
        printf("用法: %s <目录>\n", argv[0]);
        return 1;
    }

    dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

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

    closedir(dir);
    return 0;
}

编译运行

gcc readdir_test.c -o readdir_test
./readdir_test /etc

三、过滤 ...

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

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

四、递归遍历整个目录树(常用)

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

void list_dir(const char *path)
{
    DIR *dir = opendir(path);
    struct dirent *entry;
    struct stat st;

    if (!dir) return;

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

        char fullpath[1024];
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        if (stat(fullpath, &st) == 0 && S_ISDIR(st.st_mode)) {
            printf("[DIR] %s\n", fullpath);
            list_dir(fullpath);  // 递归
        } else {
            printf("[FILE] %s\n", fullpath);
        }
    }
    closedir(dir);
}

int main(int argc, char *argv[])
{
    if (argc < 2) return 1;
    list_dir(argv[1]);
    return 0;
}

五、常见结构体说明

struct dirent {
    ino_t          d_ino;
    off_t          d_off;
    unsigned short d_rename;
    unsigned char  d_type;   // 文件类型
    char           d_name[256];
};

d_type 判断文件类型

DT_DIR   // 目录
DT_REG   // 普通文件
DT_LNK   // 软链接

六、CentOS 注意事项

  • CentOS 7/8 默认使用 glibc
  • readdir线程不安全
    线程安全版本:readdir_r(已废弃,不推荐)
  • 更现代方式:
    • nftw()
    • scandir()
    • C++:std::filesystem(CentOS 8+)

七、如果你想要的是“Shell 遍历”

for f in /etc/*; do
    echo "$f"
done

如果你是想:

  • C++
  • Python
  • 只遍历某类文件(如 .log
  • 处理符号链接 / 权限问题

告诉我,我可以直接给你对应方案。

0