阅读量:4
在 Linux 中,opendir() 函数用于打开一个目录流,而不是直接获取目录的大小。要获取目录的大小,你需要遍历目录中的所有文件和子目录,并累加它们的大小。以下是一个使用 opendir()、readdir() 和 stat() 函数来获取目录大小的示例:
#include
#include
#include
#include
#include
unsigned long long get_directory_size(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
unsigned long long total_size = 0;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return 0;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
total_size += get_directory_size(full_path);
} else if (S_ISREG(statbuf.st_mode)) {
total_size += statbuf.st_size;
}
}
closedir(dir);
return total_size;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s \n" , argv[0]);
return 1;
}
unsigned long long size = get_directory_size(argv[1]);
printf("Directory size of %s: %llu bytes\n", argv[1], size);
return 0;
}
编译并运行此程序,传入一个目录路径作为参数,它将输出该目录的大小(以字节为单位)。注意,这个程序只计算普通文件的大小,不包括符号链接、设备文件等其他类型的文件。
以上就是关于“在Linux中如何用copendir获取目录大小”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm