在 Linux 下,readdir 通常指的是 POSIX 标准库函数 readdir(),用于读取目录中的条目。
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
dirp 是由 opendir() 返回的目录流指针struct dirent 的指针NULLstruct dirent 结构不同系统略有差异,但典型定义如下(Linux / glibc):
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_name实际长度由d_reclen决定,不是一个固定大小数组(历史实现中常写作char d_name[256])。
d_type 常见取值| 宏定义 | 含义 |
|---|---|
DT_REG |
普通文件 |
DT_DIR |
目录 |
DT_LNK |
符号链接 |
DT_CHR |
字符设备 |
DT_BLK |
块设备 |
DT_FIFO |
管道 |
DT_SOCK |
套接字 |
DT_UNKNOWN |
未知(需 stat) |
#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() + 锁)
若需要更底层、性能更高的接口,可使用:
getdents() / getdents64()(系统调用)如果你是想问 系统调用 getdents 返回的结构,或者 某个具体语言(如 C++ / Python)中的 readdir,可以继续问我。