在C语言中,使用readdir函数可以遍历目录中的文件和子目录。要获取文件的大小,你需要结合stat函数来获取文件的详细信息。以下是一个简单的示例,展示了如何使用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;
// 打开目录
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;
}
// 构建文件的完整路径
char path[PATH_MAX];
snprintf(path, sizeof(path), "./%s", entry->d_name);
// 获取文件状态
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
// 检查是否是常规文件
if (S_ISREG(file_stat.st_mode)) {
// 输出文件名和大小
printf("File: %s, Size: %ld bytes\n", entry->d_name, file_stat.st_size);
}
}
// 关闭目录
closedir(dir);
return EXIT_SUCCESS;
}
在这个示例中,我们首先使用opendir函数打开当前目录(.)。然后,我们使用readdir函数遍历目录中的每个条目。对于每个条目,我们使用snprintf构建文件的完整路径,并使用stat函数获取文件的状态信息。stat函数返回的信息存储在file_stat结构体中。
我们使用S_ISREG宏来检查文件是否是常规文件(而不是目录或其他类型的文件)。如果是常规文件,我们可以从file_stat.st_size获取文件的大小,并将其打印出来。
最后,我们使用closedir函数关闭目录。
请注意,这个示例假设你有足够的权限来读取目录中的文件,并且你的系统支持POSIX标准的文件和目录操作函数。如果你在使用其他编程语言,如Python或Java,获取文件大小的方法会有所不同。