在 Ubuntu 下调试 opendir() 相关代码,通常可以从代码写法、错误信息、调试工具、权限问题几个方面入手。下面给你一套实用流程。
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "usage: %s <dir>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
printf("opendir success\n");
closedir(dir);
return 0;
}
编译:
gcc test_opendir.c -o test_opendir
运行:
./test_opendir /some/dir
opendir 返回 NULL一定要看 errno
perror("opendir");
常见错误:
ENOENT:目录不存在EACCES:权限不足ENOTDIR:路径不是目录例如:
./test_opendir /etc/shadow
可能返回:
opendir: Permission denied
\0 结尾调试示例:
printf("path=[%s]\n", path);
opendir() 会跟随符号链接。
检查:
ls -l /path
如果不想跟随:
openat(AT_FDCWD, path, O_DIRECTORY | O_NOFOLLOW);
gcc -g test_opendir.c -o test_opendir
gdb ./test_opendir
break main
run /some/dir
step
next
print dir
print errno
strace ./test_opendir /some/dir
你会看到类似:
openat(AT_FDCWD, "/some/dir", O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_DIRECTORY) = 3
或失败:
openat(...) = -1 EACCES (Permission denied)
Ubuntu 常见:
检查权限:
ls -ld /path
id
尝试:
sudo ./test_opendir /path
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
| 现象 | 原因 |
|---|---|
| opendir 返回 NULL | 路径错误 / 权限不足 |
只能看到 . 和 .. |
目录为空 |
| 程序崩溃 | 未检查 NULL |
| 中文路径异常 | 编码问题(UTF-8) |
如果你愿意,可以把你的 opendir 代码 + 报错信息贴出来,我可以直接帮你逐行分析。