温馨提示×

ubuntu readdir如何遍历

小樊
46
2026-09-30 18:19:45
栏目: 智能运维

在 Ubuntu(Linux)下,readdir 通常是 C 语言 中用来读取目录内容的函数(来自 <dirent.h>)。下面从 基本用法、遍历示例、注意事项 三部分说明。


一、readdir 基本概念

readdir 用于遍历一个已经用 opendir 打开的目录:

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

DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);

struct dirent 常用成员:

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

二、最简单的遍历目录示例

遍历当前目录

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

int main() {
    DIR *dir = opendir(".");
    if (!dir) {
        perror("opendir");
        return 1;
    }

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

    closedir(dir);
    return 0;
}

编译运行:

gcc readdir_test.c -o readdir_test
./readdir_test

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

如果目录里有子目录,需要递归:

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

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    if (!dir) return;

    struct dirent *entry;
    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);
        printf("%s\n", fullpath);

        struct stat st;
        if (stat(fullpath, &st) == 0 && S_ISDIR(st.st_mode)) {
            list_dir(fullpath); // 递归
        }
    }
    closedir(dir);
}

int main() {
    list_dir(".");
    return 0;
}

四、常见问题说明

1. . 和 .. 是什么?

  • . 当前目录
  • .. 上级目录
    遍历时一定要跳过,否则会死循环。

2. readdir 不是线程安全的?

是的,readdir 不是线程安全版本,多线程请用:

readdir_r()

(现代 glibc 中 readdir 实际已较安全,但仍建议小心)

3. 只遍历某种文件?

用 d_type 判断:

if (entry->d_type == DT_DIR)   // 目录
if (entry->d_type == DT_REG)   // 普通文件

五、Shell 中的“遍历”(非 C)

如果你只是想在 Ubuntu 命令行遍历:

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

或递归:

find . -type f

如果你是指 Python / Shell / C++ 的 readdir 用法,可以告诉我具体语言,我可以给你对应示例。

0 踩