在 Debian(或者说 Linux)下,readdir 通常指 C 语言中的 readdir() 函数(来自 <dirent.h>)。
“过滤文件”一般有两种理解,下面分别说明。
readdir() 过滤文件#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
在 readdir() 返回后,自己判断文件名或类型。
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) {
printf("文件: %s\n", entry->d_name);
}
}
.txt)if (strstr(entry->d_name, ".txt")) {
printf("%s\n", entry->d_name);
}
. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
| d_type | 含义 |
|---|---|
| DT_REG | 普通文件 |
| DT_DIR | 目录 |
| DT_LNK | 符号链接 |
| DT_UNKNOWN | 未知(需 stat) |
⚠️ 注意:某些文件系统(如 NFS)d_type 可能是 DT_UNKNOWN,要用 stat()。
stat() 精确过滤struct stat st;
stat(entry->d_name, &st);
if (S_ISREG(st.st_mode)) {
// 普通文件
}
Debian 没有叫 readdir 的命令,但你可能是指:
ls + 过滤ls *.txt
ls -l | grep log
find(最强大)find . -type f -name "*.txt"
find . -type d
readdir 风格工具treefd(现代 find 替代)fd "\.txt$"
| 需求 | 方法 |
|---|---|
| 只看文件 | entry->d_type == DT_REG |
| 只看目录 | entry->d_type == DT_DIR |
| 按后缀 | strstr() |
| 排除隐藏文件 | name[0] != '.' |
| 按权限/大小 | stat() |
如果你能告诉我:
我可以直接给你完整可运行代码。