Counting Directory Size Recursively Using C Part 2

Even there’s an easier way calculating directory size ftw syscall/API

1NAME
2ftw, nftw - file tree walk
3 
4DESCRIPTION
5ftw() walks through the directory tree that is located under the directory dirpath, and calls fn() once for each entry in the tree.
6By default, directories are handled before the files and subdirectories they contain (pre-order traversal).
7 
8CONFORMING TO
9POSIX.1-2001, SVr4, SUSv1.

example code size.c

1#include <stdio.h>
2#include <errno.h>
3#include <unistd.h>
4#include <sys/types.h>
5#include <sys/stat.h>
6 
7static unsigned int total = 0;
8 
9int sum(const char *fpath, const struct stat *sb, int typeflag) {
10    total += sb->st_size;
11    return 0;
12}
13 
14int main(int argc, char **argv) {
15    if (!argv[1] || access(argv[1], R_OK)) {
16        return 1;
17    }
18    if (ftw(argv[1], &sum, 1)) {
19        perror("ftw");
20        return 2;
21    }
22    printf("%s: %u\n", argv[1], total);
23    return 0;
24}

Compile using gcc

1# gcc -o size size.c

Test:

1# ./size /root/
2/root/: 614730153

Using du command

1# du -sb /root/
2614727712       /root/

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *