在 Ubuntu / Linux 下,使用 readdir() 读取目录时,readdir 本身不会过滤文件,它只是逐个返回目录项(struct dirent)。过滤需要在代码中手动判断。
下面从 C 语言(readdir) 和 Shell(ls/find) 两个层面说明。
. 和 ..)#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
⚠️ d_type 在某些文件系统上可能不可靠,稳妥做法是用 stat()
if (entry->d_type == DT_REG)
printf("普通文件: %s\n", entry->d_name);
if (entry->d_type == DT_DIR)
printf("目录: %s\n", entry->d_name);
#include <sys/stat.h>
struct stat st;
stat(entry->d_name, &st);
if (S_ISREG(st.st_mode))
printf("普通文件: %s\n", entry->d_name);
.txt)#include <string.h>
if (strstr(entry->d_name, ".txt") != NULL)
printf("%s\n", entry->d_name);
或更严谨:
int len = strlen(entry->d_name);
if (len > 4 && strcmp(entry->d_name + len - 4, ".txt") == 0)
printf("%s\n", entry->d_name);
. 开头)if (entry->d_name[0] == '.')
continue; // 跳过隐藏文件
虽然 shell 不用 readdir(),但常用等价方式:
ls *.txt
ls -a # 含隐藏文件
ls -p | grep -v /
find . -maxdepth 1 -type f
find . -maxdepth 1 -name "*.log"
for f in *; do
[ -f "$f" ] && echo "$f"
done
| 需求 | 方法 |
|---|---|
排除 . .. |
strcmp |
| 只看普通文件 | S_ISREG |
| 只看目录 | S_ISDIR |
| 按后缀 | strstr |
| 隐藏文件 | d_name[0] == '.' |
如果你能说明:
我可以给你更精确的代码示例。