方案一:递归删除文件夹
在 Linux 上使用 C++ 删除文件夹的代码可以使用 POSIX 标准库的 头文件和系统调用的 rmdir() 和 remove() 函数。以下是一个简单的例子:
#include
#include
#include
#include
// 递归删除文件夹
bool removeDirectory(const char *path) {
DIR *dir = opendir(path);
if (dir == nullptr) {
// 打开目录失败
return false;
}
dirent *entry;
while ((entry = readdir(dir)) != nullptr) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
// 跳过当前目录和父目录
continue;
}
// 构造文件/文件夹的完整路径
std::string fullPath = std::string(path) + "/" + entry->d_name;
if (entry->d_type == DT_DIR) {
// 如果是文件夹,递归删除
if (!removeDirectory(fullPath.c_str())) {
closedir(dir);
return false;
}
} else {
// 如果是文件,直接删除
if (remove(fullPath.c_str()) != 0) {
closedir(dir);
return false;
}
}
}
// 关闭目录流
closedir(dir);
// 删除当前目录
if (rmdir(path) != 0) {
return false;
}
return true;
}
int main() {
const char *path = "/path/to/directory";
if (removeDirectory(path)) {
std::cout |