在 Ubuntu(Linux)下 opendir() 失败,一般不是函数本身的问题,而是路径、权限或环境导致的。可以按下面步骤系统排查。
opendir() 失败时返回 NULL,一定要看 errno:
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
printf("errno = %d\n", errno);
}
常见 errno:
ENOENT:路径不存在EACCES:权限不足ENOTDIR:不是目录EMFILE / ENFILE:打开文件数过多ls -ld /your/path
opendir("logs") 依赖当前工作目录:
#include <unistd.h>
char cwd[256];
getcwd(cwd, sizeof(cwd));
printf("cwd=%s\n", cwd);
ls -ld /your/path
需要 x(执行)权限才能 opendir:
drwxr-x--- user group
即使目录本身有权限,父目录也要有 x 权限
sudo ./your_program
file /your/path
如果是普通文件:
open("/file", O_RDONLY)
而不是 opendir()
ls -l /your/path
如果是软链接,且目标不存在:
symlink -> /not/exist
opendir() 会失败
Ubuntu 默认用 AppArmor:
sudo aa-status
某些服务(如 nginx、docker)限制目录访问
如果你在:
路径在宿主机存在 ≠ 容器内存在
ulimit -n
程序是否忘记 closedir()?
#include <dirent.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc < 2) return 1;
DIR *d = opendir(argv[1]);
if (!d) {
perror("opendir");
return 1;
}
closedir(d);
return 0;
}
gcc test.c -o test
./test /some/path
perror("opendir") 看 errnols -ld 路径如果你愿意,可以把:
perror 输出)贴出来,我可以直接帮你定位原因。