温馨提示×

debian readdir如何分页读取

小樊
37
2026-09-25 15:30:56
栏目: 智能运维

在 Debian(或者说 Linux 下 C/C++ 编程)里,readdir 本身不支持分页读取,它是顺序遍历目录的。如果你需要“分页读取”目录内容,常见做法有以下几种:


一、最常用做法:一次性读取,再分页(推荐)

readdir 每次返回一个 struct dirent *,你把所有条目先存起来,再在用户态做分页。

示例(C 语言)

#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);

✅ 适合高性能场景
❌ 编程复杂,不推荐一般使用


四、Shell 层面的“分页读取”(非 C)

如果你只是想在命令行分页看目录:

ls | less
ls | head -n 20
ls | tail -n +21 | head -n 20

五、总结建议

场景 推荐方式
普通程序 readdir + 数组分页
多线程 readdir + 锁
超大目录 getdents64
命令行 ls + less

如果你能说明:

  • 使用语言(C / C++ / Python)
  • 是否目录非常大(百万级文件)
  • 是否要求随机翻页

我可以给你更合适的实现方案。

0 踩