在 CentOS(Linux) 下,如果你说的 readdir 是指 C 语言里的 readdir() / readdir_r(),或者 shell 里 ls 的分页读取,下面分别说明。
readdir 分页读取目录readdir 本身不支持“分页”readdir() 是顺序读取目录项的:
DIR *dir = opendir(path);
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
它一次只返回一个目录项,没有 offset / limit 参数。
思路:
#include <dirent.h>
#include <stdio.h>
void readdir_page(const char *path, int page, int page_size) {
DIR *dir = opendir(path);
if (!dir) return;
struct dirent *entry;
int count = 0;
int start = page * page_size;
int end = start + page_size;
while ((entry = readdir(dir)) != NULL) {
if (count < start) {
count++;
continue;
}
if (count >= end)
break;
printf("%s\n", entry->d_name);
count++;
}
closedir(dir);
}
调用:
readdir_page("/var/log", 2, 100); // 第3页,每页100条
✅ 优点:简单、兼容所有 CentOS 版本
❌ 缺点:目录很大时效率一般
telldir / seekdir(不推荐)long pos = telldir(dir);
seekdir(dir, pos);
问题:
ls + head / taills /var/log | head -100
ls /var/log | tail -n +101 | head -100
ls /var/log | less
ls -1 /var/log | sort | sed -n '101,200p'
getdents 系统调用在 Linux 内部,readdir 实际调用 getdents64:
#include <sys/syscall.h>
#include <linux/dirent.h>
但一般应用层不建议直接用,除非写底层工具。
| 场景 | 推荐方式 |
|---|---|
| C 程序 | 自己计数分页 |
| Shell | `ls |
| 超大目录 | 考虑数据库或索引 |
| 稳定性 | 不要用 seekdir 分页 |
如果你能告诉我:
我可以给你更精确的方案。