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

Joh*_*ter 9 c directory size posix

是否有一个POSIX函数可以给我一个目录(包括所有子文件夹)的大小,大致相当于" du -s somepath"?

Ale*_*x B 27

$ man nftw
Run Code Online (Sandbox Code Playgroud)

名称

ftw,nftw- 文件树走

描述

ftw()遍历目录dirpath下的目录树,并fn()为树中的每个条目调用一次.默认情况下,目录在它们包含的文件和子目录之前处理(预订遍历).

符合

POSIX.1-2001,SVr4,SUSv1.

简单的例子

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

static unsigned int total = 0;

int sum(const char *fpath, const struct stat *sb, int typeflag) {
    total += sb->st_size;
    return 0;
}

int main(int argc, char **argv) {
    if (!argv[1] || access(argv[1], R_OK)) {
        return 1;
    }
    if (ftw(argv[1], &sum, 1)) {
        perror("ftw");
        return 2;
    }
    printf("%s: %u\n", argv[1], total);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)