在 Debian(以及大多数 Linux)里,readdir 报错通常不是“系统 bug”,而是用法或环境不对。下面按最常见原因 → 排查方法给你一个速查表。
readdir 是什么?readdir 是 POSIX 目录读取函数,不是 Debian 特有的:
#include <dirent.h>
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
opendir,直接 readdir❌ 错误示例:
struct dirent *ent;
readdir(NULL); // 直接崩或返回错误
✅ 正确用法:
DIR *dir = opendir("/tmp");
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
printf("%s\n", ent->d_name);
}
closedir(dir);
DIR *dir = opendir("/some/path");
if (!dir) {
perror("opendir");
}
常见错误:
/root✅ 排查:
ls -ld /some/path
readdir 当成“返回字符串”用❌ 错误:
char *name = readdir(dir); // 类型完全不对
✅ 正确:
struct dirent *ent = readdir(dir);
if (ent) {
puts(ent->d_name);
}
❌ 错误:
#include <dirent.h> // 有时找不到
✅ 正确:
extern "C" {
#include <dirent.h>
}
或确认安装了:
sudo apt install libc6-dev
closedirclosedir(dir);
readdir(dir); // 未定义行为
⚠️ DIR * 关闭后不能再使用。
Debian 的旧代码可能遇到:
#define _FILE_OFFSET_BITS 64
#include <dirent.h>
否则某些大目录可能异常。
表现为:
Bad file descriptor
Input/output error
✅ 排查:
df -h
mount | grep 目录
| 错误信息 | 含义 |
|---|---|
No such file or directory |
路径不存在 |
Permission denied |
权限不足 |
Bad file descriptor |
DIR 已关闭或非法 |
Input/output error |
文件系统异常 |
Segmentation fault |
空指针 / 未 open |
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
printf("%s\n", ent->d_name);
}
closedir(dir);
return 0;
}
编译:
gcc readdir.c -o readdir
你可以直接贴:
cat /etc/debian_version)我可以精确告诉你是哪一行、为什么、怎么改。