温馨提示×

ubuntu copendir与readdir关系

小樊
36
2026-09-02 14:47:11
栏目: 智能运维

在 Ubuntu(以及一般的 Linux/Unix 系统)中,opendirreaddir用于目录遍历的一对配套函数,它们都来自标准 C 库(dirent.h)。


一、基本关系

简单说:

  • opendir打开目录,获得一个目录流(directory stream)
  • readdir读取目录项,从目录流中逐个获取文件/子目录信息
  • 用完后要用 closedir 关闭

它们的关系是:

opendir → 得到 DIR*
readdir → 不断从 DIR* 中读
closedir → 释放资源


二、函数原型

1️⃣ opendir

#include <dirent.h>

DIR *opendir(const char *name);
  • 参数:name 是目录路径
  • 返回值:
    • 成功:返回 DIR *(目录流指针)
    • 失败:返回 NULL,并设置 errno

2️⃣ readdir

#include <dirent.h>

struct dirent *readdir(DIR *dirp);
  • 参数:dirpopendir 的返回值
  • 返回值:
    • 成功:指向 struct dirent 的指针
    • 到目录末尾或出错:返回 NULL

3️⃣ closedir

int closedir(DIR *dirp);

三、struct dirent 结构

readdir 返回的结构体通常包含:

struct dirent {
    ino_t          d_ino;     // inode 号
    off_t          d_off;     // 偏移(Linux 特有)
    unsigned short d_reclen;  // 记录长度
    unsigned char  d_type;    // 文件类型
    char           d_name[];  // 文件名
};

常用的是 d_name


四、典型使用示例

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

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

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

    closedir(dir);
    return 0;
}

五、关键注意点(Ubuntu/Linux)

1️⃣ readdir 不是线程安全的

  • 线程安全版本:readdir_r(已不推荐)
  • 现代推荐:readdir + 单线程或加锁

2️⃣ 会读到 ...

  • . 表示当前目录
  • .. 表示上级目录

3️⃣ readdir 只返回文件名

  • 不包含完整路径
  • 需要自己拼接路径

4️⃣ 不能和 stat 混用误解

  • readdir 不获取文件大小、权限
  • 需要这些信息要用 stat()

六、与系统调用的关系

  • opendir / readdirC 库封装
  • 底层实际调用:
    • open()
    • getdents64()(Linux 特有系统调用)
  • 用户一般不直接用 getdents

七、一句话总结

在 Ubuntu 中,opendir 打开目录,readdir 逐个读取目录项,两者配合完成目录遍历,最后用 closedir 关闭。

如果你愿意,我也可以讲:

  • readdir vs scandir
  • 递归遍历目录
  • opendir 失败常见原因
  • 和 Windows FindFirstFile 的对比

0