copendir
函數用于打開一個目錄流,以便讀取目錄中的條目。要計算目錄的大小,你需要遍歷目錄中的所有文件和子目錄,并累加它們的大小。以下是一個使用 copendir
和 readdir
函數計算目錄大小的示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
long long get_directory_size(const char *path) {
struct dirent *entry;
DIR *dp = opendir(path);
if (!dp) {
perror("opendir");
return -1;
}
long long size = 0;
while ((entry = readdir(dp))) {
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 st;
if (stat(full_path, &st) == -1) {
perror("stat");
closedir(dp);
return -1;
}
if (S_ISDIR(st.st_mode)) {
size += get_directory_size(full_path);
} else {
size += st.st_size;
}
}
closedir(dp);
return size;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return 1;
}
long long size = get_directory_size(argv[1]);
if (size == -1) {
fprintf(stderr, "Failed to calculate directory size\n");
return 1;
}
printf("Directory size: %lld bytes\n", size);
return 0;
}
這個程序接受一個目錄路徑作為命令行參數,并計算該目錄的大?。ㄒ宰止潪閱挝唬?。它遞歸地遍歷所有子目錄,并將每個文件的大小累加到總大小中。
編譯并運行此程序:
gcc -o dir_size dir_size.c
./dir_size /path/to/directory
請注意,這個程序沒有處理符號鏈接和其他可能的錯誤情況。在實際應用中,你可能需要根據具體需求進行相應的修改。