在 Debian(以及所有 Linux/Unix 系统) 中,readdir 是 POSIX 标准函数,其返回的是一个指向 struct dirent 的指针。
readdir 函数原型#include <dirent.h>
struct dirent *readdir(DIR *dirp);
DIR *dirp,由 opendir() 返回的目录流struct dirent 的指针NULLstruct 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是必有的。
d_type 常见取值DT_REG 普通文件
DT_DIR 目录
DT_LNK 符号链接
DT_CHR 字符设备
DT_BLK 块设备
DT_FIFO 命名管道
DT_SOCK socket
DT_UNKNOWN 未知类型
#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;
}
readdir 不是线程安全的
线程安全版本:
int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
(已逐步被废弃,推荐用 readdir + 锁)
Debian 使用的是 glibc,struct dirent 细节遵循 Linux 内核 + glibc 实现
如果你需要:
getdents / getdents64 系统调用层的结构readdir vs scandir可以继续问我。