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()
?
Asked
Active
Viewed 1,238 times
5

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278

J. Mendoza
- 91
- 7
-
1I don't think that's possible with the nftw API. – Petr Skocik Feb 04 '17 at 19:26
-
The interface to `nftw()` doesn't allow for passing arbitrary information to the callback function. Therefore, if you're going to accumulate size information, your callback function will have to make calls to one or several functions that have access to 'global variables' (variables with static or dynamically allocated duration — they might or might not be globally visible). It is mildly surprising that this wasn't handled when `ftw()` was redesigned as `nftw()`. Maybe we need an `xnftw()` (extra-new file tree walk) that takes an extra `void *` argument that is passed to the callback function. – Jonathan Leffler Feb 04 '17 at 19:39
-
I would suggest using [fts](https://dyn.manpages.debian.org/fts.3.en.html), it allows your code to control the file tree walk instead of being controlled from a callback. @JonathanLeffler Apparently it's not in POSIX yet, though my macOS man page claims "The fts utility is expected to be included in a future IEEE Std 1003.1-1988 (\`\`POSIX.1'') revision." – ephemient Feb 04 '17 at 19:43
-
@ephemient: Yup, `fts` is in BSD too — [`fts(3)`](https://www.freebsd.org/cgi/man.cgi?query=fts&sektion=3) for FreeBSD, and also available on macOS Sierra. It is not in POSIX — yet (so, not in POSIX 2016). – Jonathan Leffler Feb 04 '17 at 19:44
1 Answers
1
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;
}

J. Mendoza
- 91
- 7