在 Linux/Debian 下,readdir 通常指 通过 opendir/readdir 系列函数读取目录内容。过滤文件一般是在 应用层判断,而不是 readdir 本身支持过滤。
下面按几种常见场景说明。
readdir 过滤文件(最常见)readdir 返回目录中所有项. 和 ..#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0] == '.')
continue; // 过滤隐藏文件
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
使用 entry->d_type:
| d_type | 含义 |
|---|---|
| DT_REG | 普通文件 |
| DT_DIR | 目录 |
| DT_LNK | 符号链接 |
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
⚠️ 注意:d_type 在某些文件系统(如 NFS)上可能不可用,必要时使用 stat()。
.txt 文件#include <string.h>
if (strstr(entry->d_name, ".txt"))
printf("%s\n", entry->d_name);
或更严谨:
#include <string.h>
char *dot = strrchr(entry->d_name, '.');
if (dot && strcmp(dot, ".txt") == 0)
printf("%s\n", entry->d_name);
scandir 直接过滤(推荐)scandir 支持 过滤函数 + 自动排序。
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int filter(const struct dirent *entry) {
return entry->d_type == DT_REG;
}
int main() {
struct dirent **list;
int n = scandir(".", &list, filter, alphasort);
for (int i = 0; i < n; i++) {
printf("%s\n", list[i]->d_name);
free(list[i]);
}
free(list);
return 0;
}
✅ 这是最简洁、最推荐的方式
如果你指的是 命令行过滤 ls 输出(不是 C 代码):
ls *.txt
或
find . -maxdepth 1 -type f -name "*.txt"
| 场景 | 推荐方式 |
|---|---|
| C 程序读取目录 | opendir + readdir |
| 需要自动过滤 | scandir ✅ |
| 按类型 | d_type 或 stat() |
| 按名字 | strcmp / strstr |
| 命令行 | ls / find |
如果你愿意,可以告诉我:
我可以给你一个完全贴合你需求的示例代码。