在 Debian(或者说 Linux 下 C 语言编程)里,opendir() + readdir() 本身不能“排除文件”,它只会把目录里的所有条目读出来。
所谓“排除文件”,通常是在 读取过程中或之后进行过滤。
下面给你几种常见做法,从简单到规范。
#include <dirent.h>
#include <string.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;
// 排除特定文件
if (strcmp(entry->d_name, "test.txt") == 0)
continue;
// 排除某种后缀
if (strstr(entry->d_name, ".log"))
continue;
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
✅ 优点:简单、可控
❌ 缺点:逻辑写在代码里
#include <fnmatch.h>
if (fnmatch("*.tmp", entry->d_name, 0) == 0)
continue;
适合:
*.logfile_**.bakscandir 可以传入 过滤函数:
#include <dirent.h>
#include <stdio.h>
int filter(const struct dirent *d) {
if (strcmp(d->d_name, ".") == 0 ||
strcmp(d->d_name, "..") == 0)
return 0;
if (strstr(d->d_name, ".log"))
return 0;
return 1;
}
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);
}
✅ 推荐用于“列出并排除”
如果你是指:
遍历目录但跳过某些文件不处理
那就 只跳过,不 open():
if (strcmp(entry->d_name, "secret") == 0)
continue;
int fd = open(entry->d_name, O_RDONLY);
如果你其实是想问 Debian 命令行 怎么排除:
ls -I "*.log"
或
find . -type f ! -name "*.log"
| 场景 | 方法 |
|---|---|
| C 程序遍历目录 | readdir + if 排除 |
| 模式匹配 | fnmatch |
| 一次性列出 | scandir |
| 命令行 | ls -I / find |
如果你能说清楚:
我可以给你更精确的代码。