在 Debian(以及所有 Linux 系统)下,readdir() 本身并不能直接获取文件大小。readdir() 只返回目录项(struct dirent),其中包含:
d_nameDT_REG、DT_DIR)文件大小需要通过 stat() / lstat() 获取。
#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: %ld bytes\n", entry->d_name, st.st_size);
}
closedir(dir);
return 0;
}
readdir() 不提供大小struct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_rendtl;
unsigned char d_type; // 文件类型,不是大小
char d_name[]; // 文件名
};
stat() 获取大小st.st_size // 普通文件大小(字节)
st.st_blocks // 占用磁盘块数
lstat()如果不想跟随符号链接:
lstat(fullpath, &st);
如果你只需要文件名和大小,且目录很大:
getdents()(底层系统调用)fts* / nftw()ls -l
stat *
du -h
✅ Debian 下获取文件大小的标准方式:
readdir()拿到文件名 →stat()获取st_size
如果你需要 某一语言版本(C++ / Python / Shell) 或 递归目录示例,可以继续问我。