gpt4 book ai didi

c++ - 如何在 Linux 上用 C++ 清除目录内容(基本上,我想做 'rm -rf /*'

转载 作者:IT王子 更新时间:2023-10-29 00:02:48 26 4
gpt4 key购买 nike

我正在 Linux (Ubuntu) 上编写一个 C++ 程序。我想删除一个目录的内容。它可以是松散的文件或子目录。

本质上,我想做一些等同于

的事情
rm -rf <path-to-directory>/*

您能否建议在 C++ 中执行此操作的最佳方法以及所需的 header 。是否可以使用 sys/stat.h 或 sys/types.h 或 sys/dir.h 执行此操作?!

最佳答案

使用 nftw() (文件树遍历)函数,带有 FTW_DEPTH 标志。提供一个仅在传递的文件上调用 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);
}

如果不想删除基目录本身,更改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;
}

关于c++ - 如何在 Linux 上用 C++ 清除目录内容(基本上,我想做 'rm -rf <directorypath>/*',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3184445/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com