C++实现将一个文件夹内容拷贝至另一个文件夹
作者:野牛程序员:2023-07-20 19:42:53 C++阅读 3069
要在C++中将一个文件夹的内容拷贝到另一个文件夹,你需要使用文件和目录操作函数。在Windows下,你可以使用CopyFile和CreateDirectory等API函数来完成任务。在Linux和Unix系统中,你可以使用std::filesystem标准库来实现这个功能。
下面我将为你提供一个基于std::filesystem的跨平台示例代码,该代码可以将一个文件夹的内容拷贝到另一个文件夹。
#include <iostream>
#include <filesystem>
#include <string>
namespace fs = std::filesystem;
void copyFolder(const fs::path& src, const fs::path& dst) {
try {
// Check if source exists and is a directory
if (fs::exists(src) && fs::is_directory(src)) {
// Create the destination directory if it doesn't exist
if (!fs::exists(dst))
fs::create_directories(dst);
for (const auto& entry : fs::directory_iterator(src)) {
const auto& currentSrc = entry.path();
const auto currentDst = dst / currentSrc.filename();
if (fs::is_directory(currentSrc)) {
// Recursively copy subdirectories
copyFolder(currentSrc, currentDst);
} else {
// Copy files
fs::copy_file(currentSrc, currentDst, fs::copy_options::overwrite_existing);
}
}
} else {
std::cerr << "Source directory not found or is not a directory.\\n";
}
} catch (const std::exception& e) {
std::cerr << "Error occurred: " << e.what() << '\\n';
}
}
int main() {
// Replace these paths with your source and destination folder paths
fs::path sourceFolder = "path/to/source/folder";
fs::path destinationFolder = "path/to/destination/folder";
copyFolder(sourceFolder, destinationFolder);
std::cout << "Folder contents copied successfully!\\n";
return 0;
}请注意,代码中的源文件夹和目标文件夹路径应替换为你自己的路径。这样,当你运行程序时,它将递归地复制源文件夹中的所有内容(包括子文件夹和文件)到目标文件夹中。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C++ 将一个文件夹拷贝到另一个文件夹
- 下一篇:深拷贝c++函数
