在 Ubuntu(Linux)下使用 opendir() 出错,通常是指 C/C++ 程序调用 opendir() 返回 NULL。排查思路如下:
opendir() 声明在:
#include <dirent.h>
DIR *opendir(const char *name);
出错时返回 NULL,并设置 errno。
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <dirent.h>
DIR *dir = opendir(path);
if (dir == NULL) {
fprintf(stderr, "opendir failed: %s\n", strerror(errno));
}
常见 errno 含义:
| errno | 含义 |
|---|---|
ENOENT |
目录不存在 |
EACCES |
权限不足 |
ENOTDIR |
不是目录 |
EMFILE / ENFILE |
文件描述符耗尽 |
ENOMEM |
内存不足 |
ls -ld /your/path
✅ 确认:
printf("path = %s\n", path);
ls -ld /your/path
x(执行)权限无法进入目录✅ 解决:
chmod +x /your/path
file /your/path
如果是一个文件,opendir() 会失败。
getcwd(buf, sizeof(buf));
printf("cwd = %s\n", buf);
程序运行时目录可能不是你以为的目录。
Ubuntu 常见是 AppArmor
sudo aa-status
✅ 正确示例:
opendir("/home/user/my dir");
❌ 错误示例:
opendir("/home/user/my\ dir"); // 不能加反斜杠
ulimit -n
lsof -p <pid>
#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) {
perror("opendir");
return 1;
}
closedir(d);
return 0;
}
运行:
gcc test.c -o test
./test /some/path
errno如果你愿意,可以把:
发出来,我可以帮你精确分析。