Home > Mobile >  nftw: remove the directory content without removing the top dir itself
nftw: remove the directory content without removing the top dir itself

Time:01-14

I developed a function to recursively remove a directory with nftw():

#include <errno.h>
#include <string.h>
#include <ftw.h>     /* for nftw() */

int unlink_cb(
    const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
    if(typeflag != FTW_D) {
        return remove(fpath);
    }
    return 0;
}

int rm_rf(const char *path)
{
    return nftw(path,
                unlink_cb,
                64 /* number of simultaneously opened fds, up to OPEN_MAX */,
                FTW_DEPTH | FTW_PHYS);
}


int main(int argc, const char *argv[])
{
    rm_rf("any");
}

this will remove the directory with its content. but I want to remove only the content without removing the top directory itself.

Are there a way to add some check to skipthe remove of the top dir?

CodePudding user response:

First, the test typeflag != FTW_D is useless in this case because the FTW_DEPTH flag to nftw instructs it to traverse directories in post-order, and then nftw never passes the called routine the flag FTW_D, which indicates a directory being traversed in pre-order. For directories it is traversing in post-order, it passes FTW_DP.

You could change the test to typeflag != FTW_DP, and then the program would never remove any directory, so it would not remove the top directory of the tree.

However, to have the program remove all files and subdirectories except the top, you can use the level indicator in the struct FTW that is passed. The level member indicates the depth of the current object, zero for the top directory, one for objects in it, two for objects within those, and so on. So the test can be simply:

if (0 < ftwbuf->level)
    return remove(fpath);

Note that your program should use #include <stdio.h> to declare remove.

  •  Tags:  
  • Related