在 Ubuntu(Linux)里,opendir 是 POSIX 标准库函数,用来打开目录,定义在 <dirent.h> 中。下面给你一个从“能不能用”到“写测试程序”的完整示例。
opendir 是标准 C 库函数,一般 不需要额外安装库,只要系统有 glibc 就可以。
man opendir
如果能看到手册页,说明支持。
nano test_opendir.c
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("用法: %s <目录路径>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir 失败");
return 1;
}
printf("成功打开目录: %s\n", argv[1]);
closedir(dir);
return 0;
}
gcc test_opendir.c -o test_opendir
./test_opendir /home
✅ 正常输出:
成功打开目录: /home
❌ 错误示例:
./test_opendir /不存在的目录
输出类似:
opendir 失败: No such file or directory
#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("用法: %s <目录>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
opendir 未定义✅ 确保:
#include <dirent.h>
❌ 不要写成:
#include <sys/dir.h> // 老系统才用
./test_opendir /root
可能失败,因为权限不足。
strace ./test_opendir /tmp
可以看到 opendir 实际调用的是 openat()。
Ubuntu 下测试
opendir:写 C 程序 → 包含<dirent.h>→ 编译运行即可。
如果你是想:
可以告诉我,我给你更针对性的示例。