在 Debian(以及大多数 Linux 系统)中,readdir 是 POSIX 标准 API,用于从目录流中读取目录项。它通常在 C 语言 中使用。下面分几种常见情况说明。
readdir 用来遍历目录内容,定义在:
#include <dirent.h>
函数原型:
struct dirent *readdir(DIR *dirp);
DIR *:目录流指针(由 opendir 返回)struct dirent 的指针NULL#include <stdio.h>
#include <dirent.h>
int main(void)
{
DIR *dir;
struct dirent *entry;
dir = opendir("/tmp");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
编译:
gcc readdir_example.c -o readdir_example
运行:
./readdir_example
struct dirent {
ino_t d_ino; // inode 号
off_t d_off;
unsigned short d_reclen;
unsigned char d_type; // 文件类型
char d_name[256];// 文件名
};
| 值 | 含义 |
|---|---|
| DT_REG | 普通文件 |
| DT_DIR | 目录 |
| DT_LNK | 符号链接 |
| DT_UNKNOWN | 未知(需 stat 判断) |
示例:只列出普通文件
if (entry->d_type == DT_REG) {
printf("File: %s\n", entry->d_name);
}
⚠️ 注意:某些文件系统(如 ext4 支持,NFS 不一定)才支持 d_type。
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
int main(void)
{
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
struct stat st;
stat(entry->d_name, &st);
if (S_ISREG(st.st_mode))
printf("File: %s\n", entry->d_name);
else if (S_ISDIR(st.st_mode))
printf("Dir: %s\n", entry->d_name);
}
closedir(dir);
return 0;
}
⚠️ 不推荐使用
readdir_r(dirp, entry, &result);
原因:
readdir() 在 glibc 中已是线程安全版本如果你不是写 C 程序,而是想在 Debian 上查看目录内容:
ls
ls -l
或脚本中:
for f in *; do
echo "$f"
done
. 和 .. 吗?✅ 会,需要手动过滤:
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
❌ 不是
✅ 是 glibc 封装的库函数,底层使用 getdents 系统调用
| 语言 | 接口 |
|---|---|
| Python | os.listdir() / os.scandir() |
| C++ | std::filesystem::directory_iterator |
| Go | ioutil.ReadDir / os.ReadDir |
如果你能说明:
我可以给你更精确的示例。