在 Debian(Linux) 下,使用 readdir() 只能得到目录项(文件名 + inode 号),不能直接获取文件大小。
要获取文件大小,必须结合 stat() / lstat()。
opendir() 打开目录readdir() 读取目录项stat() 获取文件信息(含大小)st_size 就是文件大小(字节)#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():不跟随,返回链接本身大小ls -l
或
stat filename
如果你是 C++ / Python / 其他语言,或者想 按大小排序 / 递归目录,可以继续问。