在 Ubuntu(Linux)下使用 C/C++ 的 readdir() 时,错误不是通过返回值区分的,而是要通过 errno 来捕获。下面详细说明。
readdir() 的错误处理方式#include <dirent.h>
struct dirent *readdir(DIR *dirp);
struct dirent 的指针NULL,且 不设置 errnoNULL,且 设置 errno⚠️ 所以:
不能只判断
readdir() == NULL,必须配合errno
#include <stdio.h>
#include <errno.h>
#include <dirent.h>
int main() {
DIR *dir = opendir("/some/path");
if (!dir) {
perror("opendir");
return 1;
}
errno = 0; // 先清零
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
if (errno != 0) {
perror("readdir");
}
closedir(dir);
return 0;
}
✅ 关键点:
errno = 0 在循环前readdir 返回 NULL 后检查 errnoerrno != 0 才是真正错误| errno | 含义 |
|---|---|
EBADF |
dirp 不是有效的目录流 |
ENOENT |
目录在遍历中被删除 |
EACCES |
权限不足 |
ENOMEM |
内存不足 |
readdir_r(线程安全)struct dirent *result;
struct dirent entry;
errno = 0;
while (readdir_r(dir, &entry, &result) == 0 && result != NULL) {
printf("%s\n", entry.d_name);
}
if (errno != 0) {
perror("readdir_r");
}
⚠️
readdir_r在新 glibc 中已被标记为废弃,但老代码常见。
getline + scandir或 C++17 std::filesystem:
#include <filesystem>
namespace fs = std::filesystem;
for (auto &p : fs::directory_iterator("/some/path")) {
std::cout << p.path() << "\n";
}
异常即可捕获错误,比 readdir 安全很多。
✅ Ubuntu 下 readdir 错误捕获要点:
NULL 不一定出错errnoopendir 失败用 perrorerrno = 0std::filesystem如果你有 具体代码 或 遇到的错误现象,可以直接贴出来,我帮你分析。