温馨提示×

ubuntu readdir返回什么结构

小樊
43
2026-10-03 16:11:51
栏目: 智能运维

在 Ubuntu(以及其它 Linux 系统)上,readdir 是 POSIX / glibc 提供的目录读取函数,其返回的是一个指向 struct dirent 的指针。


1. readdir 函数原型

#include <dirent.h>

struct dirent *readdir(DIR *dirp);
  • 参数:DIR *dirp(由 opendir 返回)
  • 返回值:
    • 成功:指向 struct dirent 的指针
    • 失败或到达目录尾:返回 NULL

⚠️ 注意:readdir 返回的指针指向 静态分配的内存,下一次调用会被覆盖。


2. struct dirent 结构(典型 Ubuntu / glibc)

在 Ubuntu 上,结构大致如下(来自 <dirent.h>):

struct dirent {
    ino_t          d_ino;       // inode 号
    off_t          d_off;       // 下一个条目的偏移量(Linux 特有)
    unsigned short d_reclen;    // 本条记录长度
    unsigned char  d_type;      // 文件类型(不是所有文件系统都支持)
    char           d_name[256]; // 文件名(以 '\0' 结尾)
};

字段说明

字段 含义
d_ino inode 编号
d_off 目录偏移量
d_reclen 记录长度
d_type 文件类型(见下表)
d_name 文件名(不含路径)

3. d_type 常见取值

DT_REG   普通文件
DT_DIR   目录
DT_LNK   符号链接
DT_CHR   字符设备
DT_BLK   块设备
DT_FIFO  管道
DT_SOCK  套接字
DT_UNKNOWN 未知

4. 使用示例

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

int main() {
    DIR *dir = opendir(".");
    struct dirent *entry;

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

    closedir(dir);
    return 0;
}

5. 常见注意事项

  • readdir 不是线程安全的
    • 线程安全版本:readdir_r(已不推荐)
    • 新推荐:readdir + 单线程 / 加锁
  • d_name 只是文件名,不含路径
  • 遍历时需自己跳过 . 和 ..

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

  • readdir vs getdents
  • scandir
  • d_type 不可靠的情况
  • 如何用 C++ / Python 等价实现

0 踩