readdir 函数本身并不直接提供文件大小信息。它主要用于读取目录中的条目(文件和子目录)。要获取文件大小,你可以使用其他函数,如 stat 或 fstat。
以下是一个使用 readdir 和 stat 获取目录中所有文件大小的示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
char path[1024];
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录(.)和上级目录(..)
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 构建文件的完整路径
snprintf(path, sizeof(path), "./%s", entry->d_name);
// 获取文件状态
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 输出文件名和大小
printf("%s: %ld bytes\n", entry->d_name, file_stat.st_size);
}
closedir(dir);
return EXIT_SUCCESS;
}
这个示例程序首先打开当前目录(.),然后使用 readdir 读取目录中的每个条目。对于每个条目,它构建文件的完整路径,并使用 stat 函数获取文件状态。stat 结构体中的 st_size 成员包含文件大小(以字节为单位)。最后,程序输出文件名和大小。