Counting Directory Size Recursively Using C Part 2

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

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.

example code size.c

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

Compile using gcc

# gcc -o size size.c

Test:

# ./size /root/
/root/: 614730153

Using du command

# du -sb /root/
614727712       /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 *