在 Ubuntu(Linux)下,opendir 是 C 语言 中用于打开目录的标准库函数,属于 <dirent.h>。下面从基本用法 → 编译 → 示例 → 常见注意点给你讲清楚。
#include <dirent.h>
DIR *opendir(const char *name);
name 是目录路径DIR* 指针NULL,并设置 errno⚠️ opendir 只是“打开目录”,要读取内容需要用 readdir。
opendir 打开目录readdir 读取目录项closedir 关闭目录#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
保存为 listdir.c,然后:
gcc listdir.c -o listdir
./listdir
No such file or directory
✅ 检查路径是否正确
Permission denied
✅ 用 ls -ld 目录名 看权限
⚠️ 会导致文件描述符泄漏
opendir("/home/user/Documents");
#include <sys/stat.h>
struct stat st;
stat(entry->d_name, &st);
if (S_ISDIR(st.st_mode)) {
printf("[DIR] %s\n", entry->d_name);
}
lsos.listdir() / os.scandir()std::filesystem如果你想要:
告诉我,我可以给你对应版本。