在 CentOS(以及所有 Linux 系统)中,readdir 通常是 C 库函数,用于读取目录内容。它底层依赖 Linux 内核的 getdents / getdents64 系统调用。下面从使用方式、工作原理、内核层面、CentOS 相关注意点几个方面说明。
readdir 是 POSIX 标准定义的目录读取函数:
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
struct direntNULL#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir("/etc");
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
opendir(path)
open()DIR *(内部包含文件描述符和缓冲区)readdir(dirp)
direntNULLreaddir 不是系统调用,真正工作的是:
readdir() → getdents64() (内核)
不同文件系统实现不同:
内核返回的数据结构:
struct linux_dirent64 {
ino64_t d_ino;
off64_t d_off;
unsigned short d_reclen;
unsigned char d_type;
char d_name[];
};
glibc 再把它转换成 struct dirent
struct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_reclen;
unsigned char d_type;
char d_name[256];
};
d_type 示例:
| 值 | 含义 |
|---|---|
| DT_REG | 普通文件 |
| DT_DIR | 目录 |
| DT_LNK | 符号链接 |
| DT_UNKNOWN | 未知(某些 FS) |
. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
readdir 使用 DIR 内部状态readdir_r(已废弃)或加锁getdents64 一直可用
readdir 是分批读取ls 轻量很多readdir 读的是内核内存| 函数 | 说明 |
|---|---|
| readdir | 32 位 inode(老接口) |
| readdir64 | 64 位 inode(现代系统默认) |
CentOS 实际使用的是 readdir64
在 CentOS 中,
readdir是 glibc 提供的目录遍历接口,底层通过getdents64系统调用从文件系统内核中分批读取目录项,适用于高效、稳定的目录扫描。
如果你愿意,我可以:
你想深入哪一部分?