c++11删除指定目录下文件
时间: 2024-11-22 15:38:43 浏览: 67
在C++11中,标准库并没有直接提供删除文件的功能,但是你可以借助一些第三方库如Boost/filesystem或是C++17引入的<filesystem>头文件来实现这个功能。以下是使用C++17的<filesystem>库删除文件的基本步骤:
```cpp
#include <filesystem>
void delete_file(const std::string& path) {
if (!std::filesystem::exists(path)) {
// 如果文件不存在,可以忽略或抛出异常
std::cout << "File does not exist: " << path << std::endl;
return;
}
try {
std::filesystem::remove(path);
std::cout << "File deleted successfully: " << path << std::endl;
} catch (const std::filesystem::filesystem_error& e) {
std::cerr << "Error deleting file: " << e.what() << std::endl;
}
}
```
在这个例子中,`std::filesystem::exists(path)`检查文件是否存在,如果存在则调用`std::filesystem::remove(path)`尝试删除。如果删除过程中发生错误,会捕获`filesystem_error`异常并打印错误信息。
阅读全文
相关推荐

















