Как скопировать каталог с помощью Boost File System? Я попробовал boost:: filesystem:: copy_directory(), но создавал только целевой каталог и не копировал содержимое.
Как копировать каталог с помощью файловой системы Boost
Ответ 1
bool copyDir(
boost::filesystem::path const & source,
boost::filesystem::path const & destination
)
{
namespace fs = boost::filesystem;
try
{
// Check whether the function call is valid
if(
!fs::exists(source) ||
!fs::is_directory(source)
)
{
std::cerr << "Source directory " << source.string()
<< " does not exist or is not a directory." << '\n'
;
return false;
}
if(fs::exists(destination))
{
std::cerr << "Destination directory " << destination.string()
<< " already exists." << '\n'
;
return false;
}
// Create the destination directory
if(!fs::create_directory(destination))
{
std::cerr << "Unable to create destination directory"
<< destination.string() << '\n'
;
return false;
}
}
catch(fs::filesystem_error const & e)
{
std::cerr << e.what() << '\n';
return false;
}
// Iterate through the source directory
for(
fs::directory_iterator file(source);
file != fs::directory_iterator(); ++file
)
{
try
{
fs::path current(file->path());
if(fs::is_directory(current))
{
// Found directory: Recursion
if(
!copyDir(
current,
destination / current.filename()
)
)
{
return false;
}
}
else
{
// Found file: Copy
fs::copy_file(
current,
destination / current.filename()
);
}
}
catch(fs::filesystem_error const & e)
{
std:: cerr << e.what() << '\n';
}
}
return true;
}
Применение:
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
, если требования к указанным каталогам или любому каталогу в исходном каталоге не выполняются, но не если один файл не может быть скопирован.
Ответ 2
Я рассматриваю эту версию как улучшенную версию ответа @nijansen. Он также поддерживает исходные и/или целевые каталоги как относительные.
namespace fs = boost::filesystem;
void copyDirectoryRecursively(const fs::path& sourceDir, const fs::path& destinationDir)
{
if (!fs::exists(sourceDir) || !fs::is_directory(sourceDir))
{
throw std::runtime_error("Source directory " + sourceDir.string() + " does not exist or is not a directory");
}
if (fs::exists(destinationDir))
{
throw std::runtime_error("Destination directory " + destinationDir.string() + " already exists");
}
if (!fs::create_directory(destinationDir))
{
throw std::runtime_error("Cannot create destination directory " + destinationDir.string());
}
for (const auto& dirEnt : fs::recursive_directory_iterator{sourceDir})
{
const auto& path = dirEnt.path();
auto relativePathStr = path.string();
boost::replace_first(relativePathStr, sourceDir.string(), "");
fs::copy(path, destinationDir / relativePathStr);
}
}
Основными отличиями являются исключения вместо возвращаемых значений, использование recursive_directory_iterator
и boost::replace_first
для разделения общей части пути итератора и использования boost::filesystem::copy()
для правильной работы с разными типами файлов (сохранение символические ссылки, например).
Ответ 3
Вам больше не нужен boost для этой задачи, так как его библиотека файловой системы была включена в С++ std, например. добавление std::filesystem::copy
#include <exception>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::path source = "path/to/source/folder";
fs::path target = "path/to/target/folder";
try {
fs::copy(source, target, fs::copy_options::recursive);
}
catch (std::exception& e) { // Not using fs::filesystem_error since std::bad_alloc can throw too.
// Handle exception or use error code overload of fs::copy.
}
}
См. также std::filesystem::copy_options
.