在 Ubuntu(Linux)下使用 readdir 过滤目录内容,一般是在 C 语言编程中通过 opendir + readdir 实现。常见做法有几种,下面按使用场景说明。
. 和 .. 以及目录)#include <stdio.h>
#include <dirent.h>
#include <sys/stat.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;
// 过滤目录
if (entry->d_type == DT_DIR)
continue;
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
readdir 返回的 struct dirent 中有:
entry->d_type
常见取值:
| 类型 | 宏 |
|---|---|
| 普通文件 | DT_REG |
| 目录 | DT_DIR |
| 符号链接 | DT_LNK |
| 字符设备 | DT_CHR |
| 块设备 | DT_BLK |
| 套接字 | DT_SOCK |
| 管道 | DT_FIFO |
示例(只显示目录):
if (entry->d_type == DT_DIR)
printf("%s\n", entry->d_name);
⚠️ 注意:d_type 在某些文件系统(如某些网络文件系统)上可能不可靠。
如果你需要按权限、大小、时间等过滤,用 stat:
struct stat st;
stat(entry->d_name, &st);
if (S_ISREG(st.st_mode)) // 普通文件
if (S_ISDIR(st.st_mode)) // 目录
if (st.st_size > 1024) // 大于 1KB
示例:只列出可执行文件
if (stat(entry->d_name, &st) == 0) {
if (S_ISREG(st.st_mode) &&
(st.st_mode & S_IXUSR)) {
printf("%s\n", entry->d_name);
}
}
readdir 本身不支持通配符,需要自己判断:
#include <fnmatch.h>
if (fnmatch("*.txt", entry->d_name, 0) == 0)
printf("%s\n", entry->d_name);
如果只是使用而不是编程:
ls -p | grep -v /
或:
find . -maxdepth 1 -type f
| 需求 | 方法 |
|---|---|
过滤 . .. |
strcmp |
| 按类型 | d_type |
| 精确属性 | stat |
| 文件名模式 | fnmatch |
| 简单使用 | shell 命令 |
如果你是 C / C++ / Python / 某种语言 或想过滤 某种具体条件(比如后缀、大小、时间),可以告诉我,我给你写完整示例。