开发者

How to clear directory contents in c++ on Linux (basically, i want to do 'rm -rf <directorypath>/*'

I am writing a c++ program on Linux (Ubuntu). I would like to delete the contents of a directory. It can be loose files or sub-directories.

Essentially, i would like to do something equivalent to

rm -rf <path-to-directory>/*

Can you suggest the best 开发者_如何学Cway of doing this in c++ along with the required headers. Is it possible to do this with sys/stat.h or sys/types.h or sys/dir.h ?!


Use the nftw() (File Tree Walk) function, with the FTW_DEPTH flag. Provide a callback that just calls remove() on the passed file:

#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <ftw.h>
#include <unistd.h>

int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
    int rv = remove(fpath);

    if (rv)
        perror(fpath);

    return rv;
}

int rmrf(char *path)
{
    return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
}

If you don't want to remove the base directory itself, change the unlink_cb() function to check the level:

int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
    int rv;

    if (ftwbuf->level == 0)
        return 0;

    rv = remove(fpath);

    if (rv)
        perror(fpath);

    return rv;
}


Boost remove_all http://www.boost.org/doc/libs/1_31_0/libs/filesystem/doc/index.htm


system ("rm -rf <path-to-directory>");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜