在 Linux 下,readdir 本身没有“参数”让你去设置,它只是按顺序读取目录流中的下一个目录项。
你真正需要“设置”的,通常是 opendir / 目录流 / 读取方式,而不是 readdir 本身。
下面系统地说明一下。
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
| 参数 | 说明 |
|---|---|
dirp |
由 opendir() 返回的目录流指针 |
✅ 没有额外参数可以设置
✅ 每次调用返回目录中的下一个文件/子目录
#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;
}
struct dirent {
ino_t d_ino; // inode 号
off_t d_off; // 偏移(一般不关心)
unsigned short d_reclen; // 记录长度
unsigned char d_type; // 文件类型(不是所有文件系统都支持)
char d_name[256]; // 文件名
};
if (entry->d_type == DT_REG) // 普通文件
if (entry->d_type == DT_DIR) // 目录
⚠️ 注意:
d_type 不是所有文件系统都支持DT_UNKNOWN. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
if (strstr(entry->d_name, ".txt"))
printf("%s\n", entry->d_name);
❌ readdir 不支持排序
✅ 解决办法:
qsort()char *names[100];
int count = 0;
while ((entry = readdir(dir))) {
names[count++] = strdup(entry->d_name);
}
qsort(names, count, sizeof(char *),
(int (*)(const void *, const void *))strcmp);
使用:
void rewinddir(DIR *dirp);
long telldir(DIR *dirp);
void seekdir(DIR *dirp, long loc);
示例:
long pos = telldir(dir);
readdir(dir);
seekdir(dir, pos); // 回到之前位置
| 函数 | 状态 |
|---|---|
readdir |
✅ 推荐使用 |
readdir_r |
❌ 已废弃 |
原因:
readdir 是线程安全的(glibc),不需要 _r 版本。
❌ 错误理解:
“readdir 能不能设置只读普通文件?”
✅ 正确理解:
readdir 只负责读取目录项readdir 没有参数可以设置,它的行为由
opendir、目录流和你自己的代码逻辑决定。
如果你愿意,可以告诉我:
我可以直接给你完整示例代码。