溫馨提示×

在Linux中如何用copendir獲取目錄大小

小樊
37
2025-09-13 10:39:30
欄目: 智能運維

在 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;
}

編譯并運行此程序,傳入一個目錄路徑作為參數,它將輸出該目錄的大?。ㄒ宰止潪閱挝唬?。注意,這個程序只計算普通文件的大小,不包括符號鏈接、設備文件等其他類型的文件。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女