在 Debian(以及其它 Linux 系统)里,readdir 通常指 C 语言中的目录读取函数,或者命令行里容易混淆的 readdir 相关工具。下面分情况说明。
readdir(最常见)#include <dirent.h>
struct dirent *readdir(DIR *dirp);
dirp
DIR *opendir() 返回的目录流指针struct dirent 的指针NULLNULL,并设置 errno#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
编译:
gcc readdir_example.c -o readdir_example
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_name:文件名d_type:
DT_REG 普通文件DT_DIR 目录DT_LNK 符号链接示例(只列目录):
if (entry->d_type == DT_DIR) {
printf("[DIR] %s\n", entry->d_name);
}
readdir 命令如果你在 shell 里输入:
readdir
会提示:
command not found
类似功能的命令是:
lsfindtreereaddir() → 标准 C 库getdents() / getdents64() → 底层系统调用(不推荐直接用)readdir 会读到 . 和 .. 吗?会,需要自己过滤:
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
⚠️ 已不推荐,现代程序直接用 readdir + 加锁即可。
Debian 下
readdir是 C 函数,参数是opendir()返回的DIR *,用来逐个读取目录项。
如果你是指:
可以告诉我你的使用场景,我可以给你更精确的例子。