在 Ubuntu(Linux)下使用 readdir 过滤文件,通常是指 在 C/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;
}
. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
.txt)#include <string.h>
if (strstr(entry->d_name, ".txt") == NULL)
continue;
或严格判断后缀:
size_t len = strlen(entry->d_name);
if (len < 4 || strcmp(entry->d_name + len - 4, ".txt") != 0)
continue;
readdir 本身只给名字,要准确判断需要用 stat:
#include <sys/stat.h>
struct stat st;
stat(entry->d_name, &st);
if (S_ISDIR(st.st_mode)) {
// 目录
}
if (S_ISREG(st.st_mode)) {
// 普通文件
}
✅ 推荐用 fstatat 更安全(避免竞争)
fnmatch 做通配符过滤#include <fnmatch.h>
if (fnmatch("*.log", entry->d_name, 0) == 0) {
// 匹配 *.log
}
. 开头)if (entry->d_name[0] == '.')
continue;
.txt 文件DIR *dir = opendir(".");
struct dirent *e;
struct stat st;
while ((e = readdir(dir))) {
if (e->d_name[0] == '.') continue;
char path[256];
snprintf(path, sizeof(path), "./%s", e->d_name);
stat(path, &st);
if (S_ISREG(st.st_mode) &&
strstr(e->d_name, ".txt"))
printf("%s\n", e->d_name);
}
closedir(dir);
ls *.txt
import os
[f for f in os.listdir('.') if f.endswith('.txt')]
如果你能说明:
我可以给你更精确的代码。