在 Ubuntu(Linux)下使用 opendir() 时,返回 NULL(空指针)是非常常见的问题,通常不是代码 bug,而是路径或权限问题。下面系统地说一下怎么处理和排查。
opendir() 返回 NULL 的常见原因DIR *dir = opendir(path);
if (dir == NULL) {
// 出错
}
常见原因包括:
errno#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
DIR *dir = opendir(path);
if (dir == NULL) {
fprintf(stderr, "opendir failed: %s\n", strerror(errno));
}
常见 errno 含义:
| errno | 含义 |
|---|---|
| ENOENT | 目录不存在 |
| ENOTDIR | 不是目录 |
| EACCES | 权限不足 |
| EFAULT | path 为 NULL |
#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;
}
// 正常操作
closedir(dir);
return 0;
}
ls -ld /your/path
file /your/path
namei -l /your/path
如果你是普通用户:
sudo -u youruser ls /your/path
❌ 错误示例:
opendir("/home/user/Downloads/"); // 多一个斜杠一般没事,但拼写错就有事
✅ 建议:
char path[256];
snprintf(path, sizeof(path), "%s", argv[1]);
✅ 永远不要直接用 NULL
DIR *dir = opendir(path);
if (!dir) {
return -1;
}
✅ 用完必须 closedir
closedir(dir);
✅ 不要 opendir 一个文件
opendir("/etc/passwd"); // 错误
#include <filesystem>
namespace fs = std::filesystem;
if (!fs::is_directory(path)) {
// 错误处理
}
Ubuntu 下
opendir返回 NULL,99% 是路径或权限问题,用errno + perror定位最快。
如果你愿意,可以把:
发出来,我可以帮你精确分析。