在 Linux 中,opendir() 函数用于打开一个目录流,而不是直接获取目录的大小。要获取目录的大小,你需要遍历目录中的所有文件和子目录,并累加它们的大小。以下是一个使用 opendir()、readdir() 和 stat() 函数来获取目录大小的示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
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 <directory_path>\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;
}
编译并运行此程序,传入一个目录路径作为参数,它将输出该目录的大小(以字节为单位)。注意,这个程序只计算普通文件的大小,不包括符号链接、设备文件等其他类型的文件。