在 Debian(以及其它 Linux 系统)上,readdir 本身只能获取目录项(文件名、inode 号、文件类型等),不能直接获取文件大小。
要获取文件大小,需要 配合 stat / lstat 使用。
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[]; // 文件名
};
✅ 有文件名
❌ 没有文件大小
#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;
}
stat()int stat(const char *path, struct stat *buf);
struct stat {
off_t st_size; // 文件大小(字节)
};
lstat()int lstat(const char *path, struct stat *buf);
❌ 想用 readdir 直接拿大小
✅ 必须再用 stat
❌ 只判断 d_type == DT_REG 就认为一定安全
✅ 某些文件系统 d_type 可能为 DT_UNKNOWN,要 stat 确认
ls -l
或
stat *
| 功能 | 函数 |
|---|---|
| 遍历目录 | opendir / readdir |
| 获取文件大小 | stat / lstat |
| 大小字段 | st.st_size |
如果你需要:
可以继续问我。