How do I get the size of a directory in C?

情到浓时终转凉″ 提交于 2019-11-30 13:21:42

问题


Is there a POSIX function that will give me the size of a directory (including all sub-folders), roughly equivalent to "du -s somepath"?


回答1:


$ man nftw

NAME

ftw, nftw - file tree walk

DESCRIPTION

ftw() walks through the directory tree that is located under the directory dirpath, and calls fn() once for each entry in the tree. By default, directories are handled before the files and subdirectories they contain (pre-order traversal).

CONFORMING TO

POSIX.1-2001, SVr4, SUSv1.

Simple example

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



回答2:


There is no ready-made function, so you will have to make your own. You may look at the source code of the GNU implemenation of du as an example (see http://www.gnu.org/prep/ftp.html for a list of places to download from). It is in the coreutils package.

The crucial Posix calls are probably opendir, readdir, closedir, and stat.




回答3:


Result in bytes:

du -sb | grep -oE '^\s*[0-9]+'


来源:https://stackoverflow.com/questions/472697/how-do-i-get-the-size-of-a-directory-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!