在 Debian(或者说 Linux 下 C/C++ 编程)里,readdir 本身不支持分页读取,它是顺序遍历目录的。如果你需要“分页读取”目录内容,常见做法有以下几种:
readdir 每次返回一个 struct dirent *,你把所有条目先存起来,再在用户态做分页。
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#define PAGE_SIZE 10
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
char *names[1000];
int count = 0;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
names[count++] = strdup(entry->d_name);
}
closedir(dir);
// 第一页
for (int i = 0; i < PAGE_SIZE && i < count; i++) {
printf("%s\n", names[i]);
}
return 0;
}
✅ 优点:简单、可控
❌ 缺点:目录非常大时占用内存
readdir_r(线程安全,但仍不支持分页)readdir_r 只是线程安全版本,用法类似:
struct dirent entry;
struct dirent *result;
while (readdir_r(dir, &entry, &result) == 0 && result != NULL) {
// 处理 entry
}
⚠️ 注意:glibc 已标记 readdir_r 为废弃
getdents / getdents64(底层,可“批量”读取)这是 readdir 的底层系统调用,可以一次读取多个目录项,但仍不是“页码”概念。
#include <sys/syscall.h>
#include <unistd.h>
#include <linux/dirent.h>
syscall(SYS_getdents64, fd, buf, size);
✅ 适合高性能场景
❌ 编程复杂,不推荐一般使用
如果你只是想在命令行分页看目录:
ls | less
ls | head -n 20
ls | tail -n +21 | head -n 20
| 场景 | 推荐方式 |
|---|---|
| 普通程序 | readdir + 数组分页 |
| 多线程 | readdir + 锁 |
| 超大目录 | getdents64 |
| 命令行 | ls + less |
如果你能说明:
我可以给你更合适的实现方案。