在 Ubuntu 上调试 opendir(),通常是为了排查目录打不开、权限问题、路径错误、程序崩溃等。下面从常见原因、调试方法、示例代码、工具使用几个方面说明。
opendir() 基本用法回顾#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir = opendir("/tmp");
if (dir == NULL) {
perror("opendir");
return 1;
}
closedir(dir);
return 0;
}
opendir("/tmp/xxx");
❌ 返回 NULL,errno = ENOENT
opendir("/root");
❌ 返回 NULL,errno = EACCES
opendir("/etc/passwd");
❌ 返回 NULL,errno = ENOTDIR
opendir(NULL);
❌ 可能导致段错误
perror()(最常用)DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
}
输出示例:
opendir: No such file or directory
opendir: Permission denied
errno 精确判断#include <errno.h>
if (dir == NULL) {
if (errno == ENOENT)
printf("目录不存在\n");
else if (errno == EACCES)
printf("权限不足\n");
}
printf("path = [%s]\n", path);
常见坑:
gdb 调试(推荐)gcc -g test.c -o test
gdb ./test
run
bt # 查看调用栈
print path
stat() 先检查路径#include <sys/stat.h>
struct stat st;
if (stat(path, &st) == -1) {
perror("stat");
} else {
if (!S_ISDIR(st.st_mode))
printf("不是目录\n");
}
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("用法: %s <目录>\n", argv[0]);
return 1;
}
printf("尝试打开: [%s]\n", argv[1]);
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
printf("opendir 失败: %s\n", strerror(errno));
return 1;
}
printf("opendir 成功\n");
closedir(dir);
return 0;
}
| 工具 | 用途 |
|---|---|
perror() |
快速查看错误原因 |
errno |
精确判断错误类型 |
gdb |
程序崩溃、空指针 |
stat() |
判断路径是否存在及类型 |
strace |
系统调用级调试 |
strace 看系统调用strace ./test /tmp
可以看到:
openat(..., "/tmp", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_DIRECTORY) = -1 ENOENT
如果你愿意,可以把:
贴出来,我可以帮你精确定位问题。