要使用 opendir 獲取目錄的大小,你需要遍歷目錄中的所有文件和子目錄,并累加它們的大小。以下是一個示例代碼,展示了如何使用 C 語言中的 opendir、readdir 和其他相關函數來實現這一目標:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
// 遞歸計算目錄大小
off_t get_directory_size(const char *path) {
DIR *dir = opendir(path);
struct dirent *entry;
off_t total_size = 0;
if (dir == NULL) {
perror("opendir");
return -1;
}
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);
struct stat statbuf;
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 EXIT_FAILURE;
}
const char *path = argv[1];
off_t size = get_directory_size(path);
if (size >= 0) {
printf("Total size of directory '%s': %lld bytes\n", path, (long long)size);
} else {
fprintf(stderr, "Failed to calculate directory size\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
opendir:打開一個目錄流。readdir:讀取目錄流中的條目。stat:獲取文件或目錄的狀態信息。get_directory_size 函數來計算子目錄的大小。gcc -o dirsize dirsize.c
./dirsize /path/to/directory
這個程序會輸出指定目錄的總大?。ㄒ宰止潪閱挝唬?。注意,這個示例代碼假設路徑長度不超過 PATH_MAX,并且在處理符號鏈接和其他特殊文件類型時可能需要額外的處理。