在 Debian(或者说在 C 语言环境下,因为 opendir 是 POSIX 的目录操作函数)里,opendir 本身不能过滤文件,它只是打开目录,返回 DIR *。
真正“过滤”是在 readdir 循环中做判断。
下面给你几种常见做法。
#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
if (!dir) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
// 过滤掉 . 和 ..
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
// 只显示 .txt 文件
if (strstr(entry->d_name, ".txt"))
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
✅ 适合:
readdir 只给名字,类型不可靠,需用 stat
#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("FILE: %s\n", entry->d_name);
else if (S_ISDIR(st.st_mode)) // 目录
printf("DIR : %s\n", entry->d_name);
}
scandir(最推荐,自带过滤)scandir 可以直接传 过滤函数
#include <stdio.h>
#include <dirent.h>
int filter(const struct dirent *e) {
return strncmp(e->d_name, "test", 4) == 0;
}
int main() {
struct dirent **namelist;
int n = scandir(".", &namelist, filter, alphasort);
for (int i = 0; i < n; i++) {
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
}
✅ 优点:
. / ..#include <regex.h>
int filter(const struct dirent *e) {
regex_t reg;
regcomp(®, ".*\\.log$", REG_EXTENDED);
int ret = regexec(®, e->d_name, 0, NULL, 0);
regfree(®);
return ret == 0;
}
ls *.txt
或
find . -maxdepth 1 -type f -name "*.txt"
| 方法 | 是否推荐 | 说明 |
|---|---|---|
| opendir + readdir | ✅ | 基础用法 |
| stat 判断类型 | ✅ | 精确控制 |
| scandir | ⭐⭐⭐ | 最方便 |
| 正则 | ⭐⭐ | 复杂规则 |
如果你能告诉我:
我可以直接给你完整可用代码。