c++中删除带有某个字符串的文件
时间: 2024-04-11 14:27:41 浏览: 15
在C++中,可以使用标准库 `<filesystem>` 中的函数来删除带有某个字符串的文件。下面是一个示例代码:
```cpp
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
std::string targetString = "string_to_search";
std::string directoryPath = "path_to_directory";
for (const auto& entry : fs::directory_iterator(directoryPath)) {
if (entry.is_regular_file() && entry.path().filename().string().find(targetString) != std::string::npos) {
fs::remove(entry);
std::cout << "Deleted file: " << entry.path().filename() << std::endl;
}
}
return 0;
}
```
在上面的代码中,你需要将 `targetString` 替换为你要搜索的字符串,将 `directoryPath` 替换为要搜索的目录路径。然后遍历目录中的每个文件,如果文件名包含目标字符串,则使用 `std::filesystem::remove` 函数删除该文件。
请注意,这需要使用C++17或更高版本的编译器,并且需要链接C++17标准库(例如,使用 `-std=c++17` 编译选项)来支持 `<filesystem>` 头文件。