Even there’s an easier way calculating directory size ftw syscall/API
2 | ftw, nftw - file tree walk |
5 | ftw() walks through the directory tree that is located under the directory dirpath, and calls fn() once for each entry in the tree. |
6 | By default, directories are handled before the files and subdirectories they contain (pre-order traversal). |
9 | POSIX.1-2001, SVr4, SUSv1. |
example code size.c
7 | static unsigned int total = 0; |
9 | int sum( const char *fpath, const struct stat *sb, int typeflag) { |
14 | int main( int argc, char **argv) { |
15 | if (!argv[1] || access(argv[1], R_OK)) { |
18 | if (ftw(argv[1], &sum, 1)) { |
22 | printf ( "%s: %u\n" , argv[1], total); |
Compile using gcc
Test:
Using du command