在 Ubuntu(Linux)下,opendir 是 C 语言标准库(dirent.h) 中用于打开目录的函数,通常和 readdir、closedir 配合使用来遍历目录。
下面从 函数原型 → 基本用法 → 完整示例 → 常见错误 给你讲清楚。
#include <dirent.h>
DIR *opendir(const char *name);
name:要打开的目录路径(如 "/home/user" 或 ".")DIR *(目录流指针)NULL,并设置 errnostruct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
#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;
}
gcc test.c -o test
./test
dir = opendir("/home/ubuntu");
如果目录不存在或权限不足:
perror("opendir");
常见错误:
ENOENT:目录不存在EACCES:权限不足. 和 ..while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
printf("%s\n", entry->d_name);
}
#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);
else
printf("[FILE] %s\n", entry->d_name);
✅ 遍历目录
✅ 写文件管理器
✅ 扫描日志文件
✅ 写递归目录遍历程序
| 函数 | 作用 |
|---|---|
| opendir | 打开目录 |
| readdir | 读取目录项 |
| closedir | 关闭目录 |
如果你愿意,我也可以:
你想看哪一个?