在 Debian(以及其他 Linux 系统)中使用 opendir() 读取目录失败,常见原因和排查方法如下:
DIR *dir = opendir("/path/to/dir");
if (dir == NULL) {
perror("opendir");
}
如果目录不存在,opendir 返回 NULL,errno 通常是:
ENOENT:No such file or directory✅ 检查:
ls -ld /path/to/dir
即使目录存在,也可能没有访问权限。
常见 errno:
EACCES:Permission denied✅ 检查:
ls -ld /path/to/dir
id
注意:
opendir如果路径是普通文件:
ENOTDIR:Not a directory✅ 检查:
file /path/to/dir
opendir(NULL); // 错误
行为未定义,通常返回 NULL
如果是:
可能失败原因:
ENOTCONNETIMEDOUTEIO✅ 检查:
mount | grep path
dmesg | tail
opendir("/link/to/dir");
如果链接失效:
ENOENT✅ 检查:
ls -l /link/to/dir
超过 PATH_MAX:
ENAMETOOLONG相关错误:
EMFILEENFILE✅ 检查:
ulimit -n
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
printf("errno = %d\n", errno);
}
检查:
dmesg | grep apparmor
#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;
}
如果你能贴出:
perror 结果)我可以更精确地告诉你失败原因。