温馨提示×

debian readdir怎样获取大小

小樊
42
2026-09-07 10:40:37
栏目: 智能运维

在 Debian(以及其它 Linux 系统)上,readdir 本身只能获取目录项(文件名、inode 号、文件类型等),不能直接获取文件大小
要获取文件大小,需要 配合 stat / lstat 使用。


一、readdir 能拿到什么?

readdir 返回的是 struct dirent

struct dirent {
    ino_t          d_ino;
    off_t          d_off;
    unsigned short d_rendtl;
    unsigned char  d_type;   // 文件类型(DT_REG / DT_DIR ...)
    char           d_name[]; // 文件名
};

✅ 有文件名
❌ 没有文件大小


二、正确做法:readdir + stat

示例(C 语言)

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

int main(int argc, char *argv[]) {
    const char *path = ".";
    DIR *dir = opendir(path);
    if (!dir) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_REG) { // 只处理普通文件
            char fullpath[1024];
            snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

            struct stat st;
            if (stat(fullpath, &st) == 0) {
                printf("%s : %ld bytes\n", entry->d_name, st.st_size);
            } else {
                perror("stat");
            }
        }
    }

    closedir(dir);
    return 0;
}

三、关键 API 说明

1️⃣ stat()

int stat(const char *path, struct stat *buf);
struct stat {
    off_t st_size;   // 文件大小(字节)
};
  • 跟随符号链接
  • 适合大多数情况

2️⃣ lstat()

int lstat(const char *path, struct stat *buf);
  • 不跟随符号链接
  • 获取符号链接本身大小

四、常见误区

❌ 想用 readdir 直接拿大小
✅ 必须再用 stat

❌ 只判断 d_type == DT_REG 就认为一定安全
✅ 某些文件系统 d_type 可能为 DT_UNKNOWN,要 stat 确认


五、Shell 等价方式(参考)

ls -l

stat *

六、总结

功能 函数
遍历目录 opendir / readdir
获取文件大小 stat / lstat
大小字段 st.st_size

如果你需要:

  • 递归目录
  • 按大小排序
  • 只统计某类文件
  • C++ / Rust / Python 实现

可以继续问我。

0