在 Debian(或任意 Linux)下,readdir 一般指的是 readdir() / readdir_r() 这类 C 库函数(<dirent.h>)。它本身不会过滤,只能逐个读取目录项,过滤需要在代码里自己做。
下面按常见场景说明。
#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 过滤掉 . 和 ..
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
// 只显示普通文件
if (entry->d_type == DT_REG)
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
// 只显示 .txt 文件
if (strstr(entry->d_name, ".txt") == NULL)
continue;
DT_REG // 普通文件
DT_DIR // 目录
DT_LNK // 符号链接
⚠️ 注意:d_type 在某些文件系统上可能是 DT_UNKNOWN
#include <sys/stat.h>
struct stat st;
stat(entry->d_name, &st);
if (S_ISDIR(st.st_mode)) {
// 目录
}
如果你不是写 C,而是想像 readdir 一样列目录并过滤:
ls -1 | grep '\.txt$'
或:
find . -maxdepth 1 -type f
scandir 支持过滤函数 + 自动排序:
int filter(const struct dirent *e) {
return strncmp(e->d_name, ".", 1) != 0;
}
struct dirent **list;
int n = scandir(".", &list, filter, alphasort);
| 方式 | 是否过滤 | 说明 |
|---|---|---|
| readdir | ❌ | 需手动过滤 |
| scandir | ✅ | 支持 filter 函数 |
| shell | ✅ | 最方便 |
如果你能说明:
我可以给你更精确的示例。