简体   繁体   English

如何在Linux上清除c ++中的目录内容(基本上,我想做'rm -rf <directorypath> / *'

[英]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). 我正在Linux上编写一个c ++程序(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 way of doing this in c++ along with the required headers. 你能否在c ++中建议最好的方法以及所需的标题。 Is it possible to do this with sys/stat.h or sys/types.h or sys/dir.h ?! 是否可以使用sys / stat.h或sys / types.h或sys / dir.h执行此操作?

Use the nftw() (File Tree Walk) function, with the FTW_DEPTH flag. 使用带有FTW_DEPTH标志的nftw() (文件树步行)功能。 Provide a callback that just calls remove() on the passed file: 提供一个只调用传递文件上的remove()的回调:

#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: 如果您不想删除基本目录本身,请更改unlink_cb()函数以检查级别:

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;
}
system ("rm -rf <path-to-directory>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM