在 Ubuntu(或任何 Linux)上使用 opendir() 返回 NULL(空),通常不是 Ubuntu 本身的问题,而是路径、权限或代码使用方式的问题。下面按最常见原因逐一说明。
DIR *dir = opendir("/some/path");
if (dir == NULL) {
perror("opendir");
}
可能原因
✅ 检查:
ls -ld /some/path
即使目录存在,也可能无法打开:
ls -ld /root
如果你用普通用户:
opendir("/root"); // 返回 NULL
错误通常是:
opendir: Permission denied
✅ 解决:
sudo 运行opendir("/etc/passwd"); // NULL
✅ 检查:
file /etc/passwd
❌ 错误示例:
opendir("~/test"); // ~ 不会被展开
✅ 正确:
opendir("/home/user/test");
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
DIR *dir = opendir(path);
// 直接使用 dir,可能为空
✅ 正确写法:
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return -1;
}
某些 Ubuntu 程序(如 snap 应用)无法访问任意目录。
例如:
/home/user 可能受限/media 需要权限✅ 检查:
snap connections your-app
ls -l /linkdir
#include <errno.h>
#include <string.h>
printf("errno=%d: %s\n", errno, strerror(errno));
realpath /your/path
ls -ld /your/path
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir = opendir("/tmp");
if (!dir) {
perror("opendir");
return 1;
}
closedir(dir);
return 0;
}
如果你愿意,可以把:
发出来,我可以直接帮你定位具体原因。