在 Ubuntu(Linux)下使用 readdir 读取目录时,readdir 本身不会帮你过滤文件,你需要在拿到 struct dirent 后自己写判断逻辑来过滤。
下面从 C 语言 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;
}
. 和 ..while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
printf("%s\n", entry->d_name);
}
使用 entry->d_type:
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) // 普通文件
printf("FILE: %s\n", entry->d_name);
else if (entry->d_type == DT_DIR) // 目录
printf("DIR : %s\n", entry->d_name);
}
常见类型:
DT_REG 普通文件DT_DIR 目录DT_LNK 符号链接DT_UNKNOWN 未知(某些文件系统)⚠️ 注意:d_type 不一定在所有文件系统都可靠
#include <sys/stat.h>
struct stat st;
char path[256];
while ((entry = readdir(dir)) != NULL) {
snprintf(path, sizeof(path), "./%s", entry->d_name);
stat(path, &st);
if (S_ISREG(st.st_mode))
printf("REG FILE: %s\n", entry->d_name);
else if (S_ISDIR(st.st_mode))
printf("DIR : %s\n", entry->d_name);
}
.txt)#include <string.h>
while ((entry = readdir(dir)) != NULL) {
if (strstr(entry->d_name, ".txt"))
printf("%s\n", entry->d_name);
}
或:
char *dot = strrchr(entry->d_name, '.');
if (dot && strcmp(dot, ".txt") == 0)
printf("%s\n", entry->d_name);
. 开头)if (entry->d_name[0] == '.')
continue;
struct dirent **namelist;
int n = scandir(".", &namelist, NULL, alphasort);
for (int i = 0; i < n; i++) {
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
自定义过滤函数:
int filter(const struct dirent *e) {
return strcmp(e->d_name, ".") && strcmp(e->d_name, "..");
}
| 需求 | 方法 |
|---|---|
排除 . .. |
字符串判断 |
| 判断文件/目录 | d_type 或 stat |
| 后缀过滤 | strstr |
| 隐藏文件 | d_name[0] == '.' |
| 自动过滤 | scandir |
如果你有 具体过滤条件(比如“只要 .log 文件”“排除软链接”),我可以给你完整示例。