温馨提示×

ubuntu readdir如何遍历目录

小樊
45
2026-09-15 19:21:29
栏目: 智能运维

在 Ubuntu(Linux)下,使用 C/C++ 通过 readdir 遍历目录,通常配合 opendir / closedir 使用。下面给你一个完整、常用的示例。


一、基本思路

  1. opendir() 打开目录,得到 DIR*
  2. 循环调用 readdir() 读取目录项(struct dirent)
  3. 处理文件名(忽略 . 和 ..)
  4. closedir() 关闭目录

二、C 语言示例(最常用)

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

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

    if (argc < 2) {
        printf("Usage: %s <directory>\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_example.c -o readdir_example
./readdir_example /path/to/dir

三、忽略 . 和 ..

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

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

四、区分文件和目录

#include <sys/stat.h>

struct stat st;
char path[1024];

snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
stat(path, &st);

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

五、递归遍历目录(常见需求)

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

    if (!dir) return;

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

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

        printf("%s\n", full);

        struct stat st;
        stat(full, &st);
        if (S_ISDIR(st.st_mode))
            list_dir(full);
    }
    closedir(dir);
}

六、常见注意点

  • readdir 不是线程安全的
    → 多线程用 readdir_r(已逐步废弃)
  • d_name 只含文件名,不含完整路径
  • 遍历大目录时,readdir 是标准、稳定做法

如果你需要:

  • C++ 写法
  • 只遍历特定后缀文件
  • 按时间/大小排序
  • 替代方案(glob / std::filesystem)

告诉我你的具体需求即可。

0 踩