温馨提示×

debian readdir怎么获取文件大小

小樊
42
2026-09-10 08:25:13
栏目: 智能运维

Debian(Linux) 下,使用 readdir() 只能得到目录项(文件名 + inode 号),不能直接获取文件大小
要获取文件大小,必须结合 stat() / lstat()


基本思路

  1. opendir() 打开目录
  2. readdir() 读取目录项
  3. stat() 获取文件信息(含大小)
  4. st_size 就是文件大小(字节)

示例代码(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 (strcmp(entry->d_name, ".") == 0 ||
            strcmp(entry->d_name, "..") == 0)
            continue;

        char fullpath[1024];
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        struct stat st;
        if (stat(fullpath, &st) == -1) {
            perror("stat");
            continue;
        }

        printf("%s  size=%ld bytes\n",
               entry->d_name, (long)st.st_size);
    }

    closedir(dir);
    return 0;
}

关键点说明

  • readdir() → 只给文件名
  • stat() → 获取文件元数据
  • st.st_size → 文件大小(普通文件有效)
  • 如果是符号链接:
    • stat():跟随链接
    • lstat():不跟随,返回链接本身大小

如果你只是想在 shell 里看

ls -l

stat filename

如果你是 C++ / Python / 其他语言,或者想 按大小排序 / 递归目录,可以继续问。

0