c++ 删除指定目录下指定文件名文件
时间: 2023-08-26 19:05:46 浏览: 50
你可以使用 `<filesystem>` 头文件中的函数来删除指定目录下的指定文件名文件。下面是一个示例代码:
```cpp
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
std::string directoryPath = "path/to/directory";
std::string fileName = "file.txt";
fs::path filePath = fs::path(directoryPath) / fileName;
if (fs::exists(filePath)) {
try {
fs::remove(filePath);
std::cout << "File removed successfully." << std::endl;
} catch (const fs::filesystem_error& e) {
std::cout << "Failed to remove file: " << e.what() << std::endl;
}
} else {
std::cout << "File does not exist." << std::endl;
}
return 0;
}
```
在上面的代码中,你需要将 `directoryPath` 替换为你要操作的目录的路径,将 `fileName` 替换为你要删除的文件名。然后,代码会检查文件是否存在,如果存在则删除该文件,并输出相应的消息。如果文件不存在,则输出相应的消息。请确保你的编译器支持 C++17 或更高版本,并在编译时链接 `<filesystem>` 库。
请注意,在删除文件之前,请务必确保你有足够的权限执行此操作,并且要小心操作,以免意外删除重要文件。