Recursive path of a directory with the nftw function in C

1.3k Views Asked by At

I'm trying to use the nftw() function to calculate the size of a directory by the sum of some of the files. But how I do handle the sum if I cannot use global variables to store the sum of the sizes, and I have to use the function nftw()?

1

There are 1 best solutions below

1
J. Mendoza On

I've been investigating, and it is true that there is no way to pass a parameter to the nftw function to store the sum. But I've found a solution, but I do not know if it is very good.

My solution uses a "nested function" like the following:

int aux (char * name, int fd_limit, int flags) {

       int sum = 0;
       int nftwfunc (const char* filename, const struct stat* statptr, int fileflags, struct FTW* pfwt) {

           sum + = statptr-> st_size; 

       }

       nftw (name, nftwfunc, fd_limit, flags);
     
       return sum;

}