在 Ubuntu(或者说 POSIX/Linux)下,opendir() 返回 NULL(空) 通常表示打开目录失败。它本身不会“返回空目录”,而是返回一个 DIR * 指针,失败时返回 NULL。
常见原因和排查方法如下:
DIR *dir = opendir("/path/to/dir");
if (dir == NULL) {
perror("opendir");
}
如果路径不存在,opendir 会返回 NULL,并且:
errno == ENOENT
✅ 检查:
ls -ld /path/to/dir
即使目录存在,没有读/执行权限也会失败:
errno == EACCES
✅ 检查:
ls -ld /path/to/dir
需要至少:
r(读)x(进入目录)如果你传的是普通文件的路径:
errno == ENOTDIR
✅ 检查:
file /path/to/something
例如:
opendir("testdir");
但程序运行时的当前工作目录不是你以为的目录。
✅ 检查当前目录:
system("pwd");
或
pwd
errno == ENOENT 或 ELOOP
✅ 检查:
ls -l linkname
errno == ENAMETOOLONG
目录在宿主机存在,但在当前运行环境不可见。
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
int main() {
DIR *dir = opendir("/tmp");
if (dir == NULL) {
perror("opendir failed");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
r-x 权限perror("opendir")如果你愿意,可以把:
opendir 的代码perror 输出贴出来,我可以直接帮你定位问题。