C++清楚文件夹中的所有文件
时间: 2023-07-24 09:18:00 浏览: 62
你可以使用递归函数来实现清空文件夹中的所有文件。以下是一个简单的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
void clearFolder(fs::path folderPath)
{
for (auto& file : fs::directory_iterator(folderPath))
{
if (fs::is_directory(file))
{
clearFolder(file); // 递归清空子文件夹
fs::remove(file); // 删除空文件夹
}
else
{
fs::remove(file); // 删除文件
}
}
}
int main()
{
std::string folderPathStr = "C:/example/folder";
fs::path folderPath(folderPathStr);
if (fs::exists(folderPath) && fs::is_directory(folderPath))
{
clearFolder(folderPath);
std::cout << "All files in the folder have been cleared.\n";
}
else
{
std::cout << "The folder does not exist.\n";
}
return 0;
}
```
这个程序使用了 C++17 中的文件系统库,需要在编译时添加 `-std=c++17` 参数。程序首先检查文件夹是否存在并且是一个文件夹,然后调用 `clearFolder` 函数递归地清空文件夹中的所有文件。如果文件夹已经为空,函数会删除它。最后,程序输出一个消息表示文件夹中的所有文件都已经被清空。