温馨提示×

centos readdir怎样分页

小樊
47
2026-10-12 00:03:18
栏目: 智能运维

在 CentOS(Linux) 里,readdir 本身不支持分页,它是顺序读取目录项(struct dirent)的。所谓“分页”一般是在应用层做的,常见有几种做法。


一、readdir 的工作原理(先说明)

DIR *dir = opendir(path);
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
    // 逐个读取
}
closedir(dir);
  • readdir 每次返回一个目录项
  • 没有 offset / limit 概念
  • 目录很大时,要“分页”只能自己控制

二、常见 readdir 分页方案

✅ 方案 1:应用层计数分页(最常用)

适合:Web 接口、CLI 工具

#define PAGE_SIZE 100

int page = 1;
int count = 0;
int start = (page - 1) * PAGE_SIZE;
int end = start + PAGE_SIZE;

DIR *dir = opendir(path);
struct dirent *entry;

while ((entry = readdir(dir)) != NULL) {
    if (count < start) {
        count++;
        continue;
    }
    if (count >= end)
        break;

    printf("%s\n", entry->d_name);
    count++;
}
closedir(dir);

✅ 优点:简单
❌ 缺点:每次都要从头读


✅ 方案 2:保存 offset(游标分页)

适合:目录不常变、长列表

off_t last_offset = 0;
DIR *dir = opendir(path);
seekdir(dir, last_offset);

for (int i = 0; i < PAGE_SIZE; i++) {
    struct dirent *entry = readdir(dir);
    if (!entry) break;
    printf("%s\n", entry->d_name);
}

last_offset = telldir(dir);
closedir(dir);

✅ 优点:效率高
❌ 缺点:目录变动会错位


✅ 方案 3:先排序再分页(推荐)

readdir 顺序不可靠

// 读到数组
char *names[1000];
int n = 0;

DIR *dir = opendir(path);
struct dirent *e;
while ((e = readdir(dir)))
    names[n++] = strdup(e->d_name);
closedir(dir);

qsort(names, n, sizeof(char*), strcmp);

// 再分页

三、Shell 中的“分页”(非 C)

如果你是 命令行用户:

ls | sed -n '1,100p'        # 第 1 页
ls | sed -n '101,200p'     # 第 2 页

或:

ls | tail -n +101 | head -n 100

四、如果是 Web / API 场景

建议:

  • readdir → 存数组
  • 排序
  • 按 offset + limit 返回
  • 前端传 page

五、总结

方式 是否推荐 说明
readdir 原生分页 ❌ 不支持
计数分页 ✅ 简单通用
telldir/seekdir ✅ 高效但易错
先读后排序 ✅✅ 最稳妥

如果你能告诉我:

  • 是 C / C++ / Shell / Python
  • 还是 Web 接口分页

我可以给你更精确的代码。

0 踩