在 Ubuntu 下调试 opendir(),通常是指调试 POSIX 目录操作函数 opendir() / readdir() / closedir()。下面从常见错误、调试方法、示例代码、工具几个方面系统说明。
opendir() 的作用与常见错误#include <dirent.h>
DIR *opendir(const char *name);
| 错误 | 说明 |
|---|---|
| 目录不存在 | No such file or directory |
| 权限不足 | Permission denied |
| 参数 NULL | 段错误 |
| 路径错误 | 打开失败 |
| 忘记关闭目录 | 资源泄漏 |
失败时返回 NULL,并设置 errno。
perror()#include <stdio.h>
#include <dirent.h>
#include <errno.h>
int main() {
DIR *dir = opendir("/tmp/test");
if (dir == NULL) {
perror("opendir failed");
return 1;
}
closedir(dir);
return 0;
}
✅ perror() 会输出:
opendir failed: No such file or directory
errno 精确判断#include <errno.h>
#include <string.h>
if (dir == NULL) {
printf("opendir error: %s\n", strerror(errno));
}
opendirgcc -g opendir_test.c -o opendir_test
gdb ./opendir_test
break main
run
step
print dir
backtrace
opendir 返回 NULLp dir
如果返回 0x0,说明失败,再检查 errno:
p errno
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <dir>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
运行:
./test /tmp
printf("Opening dir: [%s]\n", path);
ls -ld /tmp/test
ls -l /tmp/test
strace 看系统调用strace ./opendir_test /tmp/test
可以看到:
openat(..., "/tmp/test", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_DIRECTORY) = -1 ENOENT
| 问题 | 说明 |
|---|---|
| snap 限制 | snap 程序可能无法访问某些目录 |
| WSL | Windows 路径映射问题 |
| 符号链接 | opendir 可打开,但路径要解析正确 |
✅ 先检查返回值
✅ 用 perror() 或 errno
✅ GDB 看函数返回值
✅ strace 看系统调用失败原因
✅ 确认路径和权限
如果你可以贴出:
opendir 的相关代码我可以帮你精确定位问题。