在 Debian(以及其它 Linux 系统)里,readdir() 相关函数出错时,错误码是通过全局变量 errno 来查看的,而不是返回值本身。
下面分几种常见情况说明。
readdir()#include <dirent.h>
struct dirent *readdir(DIR *dirp);
struct dirent *NULLNULL 不一定表示错误errno 不变(通常为 0)所以判断方式应该是:
errno = 0;
struct dirent *entry = readdir(dirp);
if (entry == NULL) {
if (errno != 0) {
perror("readdir");
} else {
// 正常结束
}
}
| errno | 含义 |
|---|---|
EBADF |
目录流无效(DIR* 已关闭或非法) |
ENOENT |
目录在遍历过程中被删除 |
EIO |
I/O 错误(磁盘/文件系统问题) |
ENOMEM |
内存不足 |
EINVAL |
参数非法(如 NULL 指针) |
perror()(最常用)perror("readdir");
输出示例:
readdir: No such file or directory
strerror(errno)#include <string.h>
#include <errno.h>
printf("error: %s\n", strerror(errno));
printf("errno = %d\n", errno);
man errno
man readdir
grep EBADF /usr/include/asm-generic/errno*.h
int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
0errno 值int ret = readdir_r(dirp, &ent, &res);
if (ret != 0) {
fprintf(stderr, "readdir_r error: %s\n", strerror(ret));
}
❌ 错误写法:
if (!readdir(dirp)) {
perror("readdir"); // 可能误报
}
✅ 正确写法:
errno = 0;
if (!readdir(dirp) && errno) {
perror("readdir");
}
如果你愿意,可以贴一段 具体的 C 代码或报错信息,我可以帮你精确定位是哪个 errno、为什么出现。