在 CentOS(以及所有 Linux 系统)中,readdir 并不是一条命令,而是 C 语言标准库函数,用于读取目录内容。下面从 原理、示例、编译、常见用法 几个方面说明。
readdir 是 POSIX 标准 API,定义在:
#include <dirent.h>
用于遍历一个目录中的文件和子目录。
函数原型:
struct dirent *readdir(DIR *dirp);
返回值:
struct dirent *NULL#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[])
{
DIR *dir;
struct dirent *entry;
if (argc < 2) {
printf("用法: %s <目录>\n", argv[0]);
return 1;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
sudo yum install -y gcc
gcc readdir.c -o readdir
./readdir /etc
输出示例:
.
..
passwd
hosts
fstab
...
struct dirent {
ino_t d_ino; // inode 号
off_t d_off;
unsigned short d_reclen;
unsigned char d_type; // 文件类型
char d_name[256]; // 文件名
};
⚠️ d_type 不是所有文件系统都支持。
. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
✅ 正确做法:
closedir(dir);
旧代码中常见 readdir_r,但不推荐使用(线程安全也不保证更好):
// 不推荐
readdir_r(dir, &entry, &result);
CentOS 中没有 readdir 命令,但等价命令有:
ls
tree
find
例如:
ls /etc
find /etc -maxdepth 1
✅ 在 CentOS 中实现 readdir:
opendir / readdir / closedirgcc如果你是想:
可以直接告诉我,我可以继续深入。