首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C中获取目录的大小?

要在C语言中获取目录的大小,可以使用以下方法:

  1. 使用 opendirreaddir 函数遍历目录中的所有文件和子目录。
  2. 对每个文件和子目录,使用 stat 函数获取其大小和类型。
  3. 累加所有文件和子目录的大小,得到目录的总大小。

以下是一个示例代码:

代码语言:c
复制
#include <dirent.h>
#include <sys/stat.h>
#include<stdio.h>

long long get_directory_size(const char *path) {
    long long size = 0;
    struct dirent *entry;
    DIR *dir = opendir(path);

    if (dir == NULL) {
        perror("Failed to open directory");
        return -1;
    }

    while ((entry = readdir(dir)) != NULL) {
        struct stat statbuf;
        const char *entry_path = entry->d_name;
        lstat(entry_path, &statbuf);

        if (S_ISREG(statbuf.st_mode)) {
            size += statbuf.st_size;
        } else if (S_ISDIR(statbuf.st_mode)) {
            if (strcmp(entry_path, ".") != 0 && strcmp(entry_path, "..") != 0) {
                size += get_directory_size(entry_path);
            }
        }
    }

    closedir(dir);
    return size;
}

int main() {
    const char *path = ".";
    long long size = get_directory_size(path);
    printf("Directory size: %lld bytes\n", size);
    return 0;
}

这个代码示例定义了一个 get_directory_size 函数,它接受一个目录路径作为参数,并返回该目录的大小(以字节为单位)。在 main 函数中,我们调用这个函数并打印结果。

需要注意的是,这个代码示例可能会遇到符号链接循环的问题,因为它会递归地遍历所有子目录。如果目录中存在循环符号链接,这个函数可能会陷入死循环。为了避免这个问题,可以使用 fts 函数族代替 opendirreaddir 函数,或者使用一个哈希表来记录已经访问过的目录。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券