c++实现移动文件和目录带恢复功能
作者:野牛程序员:2023-07-16 14:45:01 C++阅读 3016
以下是一个使用C++实现文件和目录的移动和恢复功能的示例代码:
#include <iostream>
#include <fstream>
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
void moveFile(const std::string& sourcePath, const std::string& destinationPath)
{
try {
fs::rename(sourcePath, destinationPath);
} catch (const fs::filesystem_error& e) {
std::cerr << "Error moving file: " << e.what() << std::endl;
}
}
void moveDirectory(const std::string& sourcePath, const std::string& destinationPath)
{
try {
fs::rename(sourcePath, destinationPath);
} catch (const fs::filesystem_error& e) {
std::cerr << "Error moving directory: " << e.what() << std::endl;
}
}
void recoverFile(const std::string& sourcePath, const std::string& destinationPath)
{
try {
fs::rename(sourcePath, destinationPath);
} catch (const fs::filesystem_error& e) {
std::cerr << "Error recovering file: " << e.what() << std::endl;
}
}
void recoverDirectory(const std::string& sourcePath, const std::string& destinationPath)
{
try {
fs::rename(sourcePath, destinationPath);
} catch (const fs::filesystem_error& e) {
std::cerr << "Error recovering directory: " << e.what() << std::endl;
}
}
int main()
{
std::string sourcePath = "path/to/source";
std::string destinationPath = "path/to/destination";
std::string recoveryPath = "path/to/recovery";
// 移动文件或目录到目标位置
moveFile(sourcePath, destinationPath);
// 或者
// moveDirectory(sourcePath, destinationPath);
// 在需要恢复时,将文件或目录从目标位置移回源位置
recoverFile(destinationPath, recoveryPath);
// 或者
// recoverDirectory(destinationPath, recoveryPath);
return 0;
}请注意,此示例使用C++17中的实验性文件系统库(std::experimental::filesystem)。在某些编译器中,可能需要将编译选项设置为-lstdc++fs以链接该库。此外,还需要根据实际需求修改源路径、目标路径和恢复路径。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:arduino检测揉捏传感器
- 下一篇:C++移动文件到指定目录并修改文件名
