在 Ubuntu(或者说 Linux 下使用 C/C++)里,opendir() 失败通常和路径、权限、文件系统状态有关。下面按常见原因系统说明一下。
opendir() 返回 NULL 时你在看什么?opendir() 失败时:
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
}
一定要配合 perror() 或 errno 看原因,例如:
No such file or directoryPermission deniedNot a directoryopendir("/home/user/nonexist_dir");
错误:
No such file or directory
✅ 解决:
stat() 或 ls 检查opendir("/etc/passwd");
错误:
Not a directory
✅ 解决:
opendir() 只能用于目录open() / fopen()opendir("/root");
错误:
Permission denied
Ubuntu 默认:
/rootsudo✅ 解决:
ls -ld 目录 看权限sudo ./your_programopendir("/tmp/broken_link");
错误:
No such file or directory
✅ 解决:
ls -l 检查软链接realpath() 解析opendir("/home/user/my dir");
如果字符串写错:
"/home/user/my dir" // 实际被截断
✅ 解决:
例如:
opendir("/mnt/nas");
如果 NAS 没挂载:
No such file or directory
或
Permission denied
✅ 解决:
mount | grep 路径极端情况:
✅ 解决:
dmesgfsck#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() 看 errno?如果你愿意,可以把:
perror() 输出发出来,我可以直接帮你定位是哪一类问题。