linux

如何使用copendir获取目录大小

小樊
46
2025-09-05 10:04:27
栏目: 编程语言

copendir 函数用于打开一个目录流,以便读取目录中的条目。要计算目录的大小,你需要遍历目录中的所有文件和子目录,并累加它们的大小。以下是一个使用 copendirreaddir 函数计算目录大小的示例:

#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

请注意,这个程序没有处理符号链接和其他可能的错误情况。在实际应用中,你可能需要根据具体需求进行相应的修改。

0
看了该问题的人还看了