Removing a non empty directory programmatically in C or C++

后端 未结 8 2463
一生所求
一生所求 2020-11-27 16:50

How to delete a non empty directory in C or C++? Is there any function? rmdir only deletes empty directory. Please provide a way without using any external library.

8条回答
  •  萌比男神i
    2020-11-27 17:22

    If you are using a POSIX compliant OS, you could use nftw() for file tree traversal and remove (removes files or directories). If you are in C++ and your project uses boost, it is not a bad idea to use the Boost.Filesystem as suggested by Manuel.

    In the code example below I decided not to traverse symbolic links and mount points (just to avoid a grand removal:) ):

    #include 
    #include 
    #include 
    
    static int rmFiles(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb)
    {
        if(remove(pathname) < 0)
        {
            perror("ERROR: remove");
            return -1;
        }
        return 0;
    }
    
    int main(int argc, char *argv[])
    {
        if (argc != 2)
        {
            fprintf(stderr,"usage: %s path\n",argv[0]);
            exit(1);
        }
    
        // Delete the directory and its contents by traversing the tree in reverse order, without crossing mount boundaries and symbolic links
    
        if (nftw(argv[1], rmFiles,10, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) < 0)
        {
            perror("ERROR: ntfw");
            exit(1);
        }
    
        return 0;
    }
    

提交回复
热议问题