在 Debian(以及其它 Linux 系统)里,opendir 本身只是“打开目录”,真正“遍历目录”需要配合 readdir / closedir 使用。下面给你一个完整、可运行、常见的用法示例。
#include <dirent.h>
#include <stdio.h>
DIR *dir = opendir(path); // 打开目录
if (!dir) { perror("opendir"); return; }
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir); // 关闭目录
#include <stdio.h>
#include <dirent.h>
int main(void)
{
DIR *dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
编译:
gcc listdir.c -o listdir
./listdir
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void list_dir(const char *path)
{
DIR *dir = opendir(path);
if (!dir) return;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
char full[1024];
snprintf(full, sizeof(full), "%s/%s", path, entry->d_name);
printf("%s\n", full);
struct stat st;
if (stat(full, &st) == 0 && S_ISDIR(st.st_mode)) {
list_dir(full); // 递归
}
}
closedir(dir);
}
int main(void)
{
list_dir(".");
return 0;
}
opendir 返回 NULL?通常是:
用 perror("opendir") 看原因。
readdir 返回的内容struct dirent 中常用字段:
entry->d_name // 文件名
entry->d_type // 文件类型(DT_DIR / DT_REG 等)
. 和 .. 也会遍历到,需要手动跳过。
可以用 <filesystem>(C++17):
#include <filesystem>
namespace fs = std::filesystem;
for (auto &p : fs::directory_iterator("."))
std::cout << p.path() << "\n";
如果你愿意,我可以给你:
getdents 更高效的方式只要告诉我你的使用场景。