在 Debian(以及其它 Linux 系统)上,readdir() 本身不会自动忽略隐藏文件,需要你在代码里手动过滤。
在 Linux 中,以 . 开头的文件/目录是隐藏文件,例如:
.bashrc.cachereaddir() 忽略隐藏文件#include <dirent.h>
#include <stdio.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (!dir) return 1;
while ((entry = readdir(dir)) != NULL) {
// 忽略隐藏文件
if (entry->d_name[0] == '.')
continue;
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
✅ 关键点:
if (entry->d_name[0] == '.')
continue;
. 和 ..(推荐). 和 .. 也是以 . 开头的,但也常被单独排除:
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
虽然不是 readdir(),但常用:
ls -A
find . -maxdepth 1 -name '[^.]*'
#include <filesystem>
namespace fs = std::filesystem;
for (const auto& p : fs::directory_iterator(".")) {
if (p.path().filename().string()[0] == '.')
continue;
std::cout << p.path() << "\n";
}
| 方法 | 是否自动忽略隐藏文件 |
|---|---|
readdir() |
❌ 需要手动过滤 |
ls -A |
✅ |
std::filesystem |
❌ 需手动判断 |
如果你告诉我你用的是 C / C++ / Python / Shell,我可以给你更精确的示例。