void CopyRecursive(fs::path src, fs::path dst)
{
//Loop through all the dirs
for (auto dir : fs::recursive_directory_iterator(src))
{
//copy the path's string to store relative path string
std::wstring relstr = dir.path().wstring();
//remove the substring matching the src path
//this leaves only the relative path
relstr.erase(0, std::wstring(src).size());
//combine the destination root path with relative path
fs::path newFullPath = dst / relstr;
//Create dir if it's a dir
if (fs::is_directory(newFullPath))
{
fs::create_directory(newFullPath);
}
//copy the files
fs::copy(dir.path(), newFullPath, fs::copy_options::recursive | fs::copy_options::overwrite_existing);
}
}
5条答案
按热度按时间bogh5gae1#
这是我使用的基于Doineann代码的非Boost版本,我使用std::filesystem,但不能使用简单的
fs::copy(src, dst, fs::copy_options::recursive);
,因为我想在循环中根据文件扩展名过滤哪些文件被复制。relstr.erase(0, std::wstring(src).size());
是另一个应答中使用的boost::replace_first()调用的有效无Boost替换kzmpq1sx2#
使用Boost库将一个目录的内容复制到另一个目录的C++示例程序:
在这个程序中,我们使用Boost的文件系统库来访问和操作文件和目录。程序检查源目录是否存在,如果不存在则创建目标目录。然后迭代源目录中的所有文件,并使用
fs::copy_file()
函数将每个文件复制到目的目录。fs::copy_option::overwrite_if_exists
标志用于覆盖目标目录中的现有文件。q0qdq0h23#
用法:
copyDir(boost::filesystem::path("/home/nijansen/test"), boost::filesystem::path("/home/nijansen/test_copy"));
(Unix)copyDir(boost::filesystem::path("C:\\Users\\nijansen\\test"), boost::filesystem::path("C:\\Users\\nijansen\\test2"));
(Windows操作系统)据我所知,最坏的情况是什么也没发生,但我不会承诺任何事情!使用风险自担。
请注意,您要复制到的目录不能存在。如果您要复制的目录中的目录无法读取(想想权限管理),它们将被跳过,但其他目录仍应复制。
更新
根据注解重构了函数。此外,函数现在返回成功结果。如果不满足给定目录或源目录中任何目录的要求,它将返回
false
,但如果无法复制单个文件,则不会返回false
。ljo96ir54#
从C++17开始,您不再需要提升此操作,因为文件系统已添加到标准中。
使用
std::filesystem::copy
另请参见
std::filesystem::copy_options
。fnx2tebb5#
我认为这个版本是@nijansen答案的改进版本,它还支持源目录和/或目标目录是相对的。
主要的区别是异常而不是返回值,使用
recursive_directory_iterator
和boost::replace_first
剥离迭代器路径的公共部分,以及依赖boost::filesystem::copy()
对不同的文件类型做正确的事情(例如,保留符号链接)。