在 Ubuntu(或其他 Linux 系统)里,opendir() 失败通常由以下几类原因导致。你可以结合 errno 来判断具体原因。
opendir() 基本说明#include <dirent.h>
DIR *opendir(const char *name);
DIR *NULL,并设置 errno一定要看 errno:
#include <errno.h>
#include <string.h>
#include <stdio.h>
DIR *dir = opendir(path);
if (!dir) {
fprintf(stderr, "opendir failed: %s\n", strerror(errno));
}
errno = ENOENT (No such file or directory)
检查:
/✅ 解决:
ls -ld /your/path
errno = ENOTDIR (Not a directory)
例如:
opendir("/etc/passwd");
✅ 解决:
file /your/path
errno = EACCES (Permission denied)
常见于:
/root✅ 解决:
ls -ld /your/path
sudo -u youruser ls /your/path
errno = ENAMETOOLONG
Ubuntu 默认路径上限约 4096 字节
errno = EMFILE / ENFILE
程序没 closedir(),导致 fd 泄漏
✅ 解决:
closedir()ulimit -nerrno = EIO / EHOSTUNREACH
Ubuntu 挂载 Windows 或网络磁盘时常见
✅ 检查:
mount | grep yourpath
df -h
Ubuntu 默认用 AppArmor
例如:
✅ 检查:
dmesg | grep apparmor
如果你在 snap 版程序里调用 opendir():
~/、/mnt、/media 等特定目录✅ 表现:
Permission denied✅ 解决:
snap connectperror("opendir");
或:
strace ./your_program
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc < 2) return 1;
DIR *d = opendir(argv[1]);
if (!d) {
printf("fail: %s\n", strerror(errno));
return 1;
}
closedir(d);
return 0;
}
如果你愿意,可以把:
strerror(errno))发出来,我可以直接帮你定位 ✅