温馨提示×

debian readdir返回什么结构体

小樊
37
2026-10-24 22:56:20
栏目: 智能运维

在 Debian(以及所有 Linux/Unix 系统) 中,readdir 是 POSIX 标准函数,其返回的是一个指向 struct dirent 的指针。


1. readdir 函数原型

#include <dirent.h>

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

2. struct dirent 结构体(Debian / glibc)

在 Debian(使用 glibc)中,struct dirent 通常定义如下(来自 <dirent.h>):

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

⚠️ 注意:不同系统字段可能略有差异,但 d_ino 和 d_name 是必有的。


3. d_type 常见取值

DT_REG   普通文件
DT_DIR   目录
DT_LNK   符号链接
DT_CHR   字符设备
DT_BLK   块设备
DT_FIFO  命名管道
DT_SOCK  socket
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 不是线程安全的
    线程安全版本:

    int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
    

    (已逐步被废弃,推荐用 readdir + 锁)

  • Debian 使用的是 glibc,struct dirent 细节遵循 Linux 内核 + glibc 实现


如果你需要:

  • getdents / getdents64 系统调用层的结构
  • readdir vs scandir
  • 如何判断文件类型

可以继续问我。

0 踩