在 Ubuntu(Linux)下,opendir() 打不开目录,通常不是函数本身的问题,而是路径、权限或程序运行环境导致的。下面按最常见原因逐一说明,并给出排查方法。
opendir 返回 NULL 的常见原因opendir() 失败时会返回 NULL,并设置 errno。第一步一定先看 errno:
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
printf("errno = %d\n", errno);
}
No such file or directory (ENOENT)
检查:
ls -ld /your/path
注意:
/✅ 解决:使用绝对路径,或先用 getcwd() 确认当前目录。
Permission denied (EACCES)
即使你是目录的“里面”有读权限,如果父目录没有执行权限(x),也打不开。
检查权限:
namei -l /path/to/dir
示例问题:
drwxr-x--- user user dir
但程序以其他用户运行(如 www-data、root 之外)
✅ 解决:
chmod +x /parent/path
chmod +r dir
Not a directory (ENOTDIR)
file /path
✅ 解决:确认你传的是目录,而不是普通文件。
No such file or directory
ls -l /path
✅ 解决:修复或删除无效软链接。
比如:
此时:
~ 可能不存在✅ 解决:
printf("uid=%d\n", getuid());
opendir("/home/user/我的目录");
✅ 确保:
Ubuntu 常见是 AppArmor
检查:
sudo aa-status
✅ 解决:放宽配置或换目录(如 /tmp 测试)
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *d = opendir("/tmp");
if (!d) {
perror("opendir");
return 1;
}
closedir(d);
printf("ok\n");
return 0;
}
gcc test.c -o test
./test
perror("opendir") 看错误信息x 权限如果你愿意,可以把:
opendir 代码perror 输出贴出来,我可以直接帮你定位是哪一类问题。