在 Ubuntu(Linux)下使用 readdir 读取目录时,过滤通常有两种做法:
opendir + 自定义逻辑过滤(如按名称、类型)下面用 C 语言 示例说明(这是 readdir 的标准用法)。
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
.txt 文件#include <stdio.h>
#include <string.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strstr(entry->d_name, ".txt")) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
readdir 返回的 d_type 可用于类型判断(Linux 支持):
if (entry->d_type == DT_REG) // 普通文件
if (entry->d_type == DT_DIR) // 目录
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
printf("[DIR] %s\n", entry->d_name);
}
}
⚠️ 如果
d_type == DT_UNKNOWN,需要用stat()进一步判断
#include <sys/stat.h>
struct stat st;
stat(entry->d_name, &st);
if (S_ISREG(st.st_mode)) {
// 普通文件
}
如果你只是想用命令过滤:
ls *.txt
或
find . -maxdepth 1 -name "*.txt"
| 需求 | 方法 |
|---|---|
| 按后缀 | strstr / strcmp |
| 隐藏文件 | d_name[0] == '.' |
| 目录 | d_type == DT_DIR |
| 普通文件 | d_type == DT_REG |
| 精确类型 | stat() |
如果你是指 C++ / Python / Shell / 某个具体框架 的 readdir,告诉我,我可以给对应示例。