linux

如何用copendir获取目录大小

小樊
42
2025-06-13 23:52:23
栏目: 编程语言

要使用 opendir 获取目录的大小,你需要遍历目录中的所有文件和子目录,并累加它们的大小。以下是一个示例代码,展示了如何使用 C 语言中的 opendirreaddir 和其他相关函数来实现这一目标:

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

说明:

  1. opendir:打开一个目录流。
  2. readdir:读取目录流中的条目。
  3. stat:获取文件或目录的状态信息。
  4. 递归:如果遇到子目录,递归调用 get_directory_size 函数来计算子目录的大小。
  5. 累加大小:对于普通文件,累加其大小;对于目录,递归计算其大小。

编译和运行:

gcc -o dirsize dirsize.c
./dirsize /path/to/directory

这个程序会输出指定目录的总大小(以字节为单位)。注意,这个示例代码假设路径长度不超过 PATH_MAX,并且在处理符号链接和其他特殊文件类型时可能需要额外的处理。

0
看了该问题的人还看了