在 Ubuntu(Linux)下使用 opendir() 出错,通常是因为目录不存在、权限不足或路径写法有问题。下面按常见原因和排查步骤来说明。
opendir() 返回 NULL 时怎么查错opendir() 失败时会返回 NULL,并且设置 errno。
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
int main() {
DIR *dir = opendir("/some/path");
if (dir == NULL) {
perror("opendir");
printf("errno = %d\n", errno);
return 1;
}
closedir(dir);
return 0;
}
错误信息:
opendir: No such file or directory
✅ 解决:
ls -ld /some/path
错误信息:
opendir: Permission denied
✅ 解决:
ls -ld /some/path
r 或 x 权限sudo 测试(仅测试,不推荐程序用 root)错误信息:
opendir: Not a directory
✅ 解决:
file /some/path
❌ 错误:
opendir("/home/user/my dir");
✅ 正确(C 字符串):
opendir("/home/user/my dir");
(C 字符串本身没问题,关键是 shell / 参数传参时不要截断)
❌ 错误:
opendir("C:\\Users\\test");
✅ Linux 路径:
opendir("/home/user/test");
确保包含头文件:
#include <dirent.h>
编译:
gcc test.c -o test
perror("opendir")?你可以把:
perror 输出)发出来,我可以精准帮你定位问题。