(1)文件复制
#include "stdafx.h"
#include <iostream>
#include <string>
#include "boost/filesystem.hpp"
using namespace std;
namespace bfs = boost::filesystem;
int main(int argc, char* argv[])
{
string rawFile= "D:/file/raw.txt";
string copyFile="D:/file/copy.txt";
bfs::copy_file(rawFile,copyFile,bfs::copy_option::overwrite_if_exists);
return 0;
}
注:其中bfs::copy_option为复制选项,若文件存在进行复制。
(2)文件夹复制
#include "stdafx.h"
#include <iostream>
#include <string>
#include "boost/filesystem.hpp"
#include "boost/algorithm/string.hpp"
using namespace std;
namespace bfs = boost::filesystem;
void copyDirector(const string& strSourceDir, const string& strDestDir); // 函数声明
int main(int argc, char* argv[])
{
string rawDir = "D:/raw/";
string copyDir = "D:/copy/";
copyDirector(rawDir, copyDir);
return 0;
}
void copyDirector(const string& strSourceDir, const string& strDestDir)
{
boost::filesystem::recursive_directory_iterator end; //设置遍历结束标志,用recursive_directory_iterator即可循环的遍历目录
boost::system::error_code ec;
for (boost::filesystem::recursive_directory_iterator pos(strSourceDir); pos != end; ++pos)
{
//过滤掉目录和子目录为空的情况
if(boost::filesystem::is_directory(*pos))
continue;
std::string strAppPath = boost::filesystem::path(*pos).string();
std::string strRestorePath;
//replace_first_copy在algorithm/string头文件中,在strAppPath中查找strSourceDir字符串,找到则用strDestDir替换,替换后的字符串保存在一个输出迭代器中
size_t strSourceDirLength = strSourceDir.length();
string strSourceDirNew = strSourceDir;
if (strSourceDir[strSourceDirLength-1]=='/')
{
strSourceDirNew = strSourceDirNew.erase(strSourceDirLength-1,1);
}
size_t strDestDirLength = strDestDir.length();
string strDestDirNew = strDestDir;
if (strDestDir[strDestDirLength-1]=='/')
{
strDestDirNew = strDestDirNew.erase(strDestDirLength-1,1);
}
boost::replace_first_copy(std::back_inserter(strRestorePath), strAppPath, strSourceDirNew, strDestDirNew);
if(!boost::filesystem::exists(boost::filesystem::path(strRestorePath).parent_path()))
{
boost::filesystem::create_directories(boost::filesystem::path(strRestorePath).parent_path(), ec);
}
boost::filesystem::copy_file(strAppPath, strRestorePath, bfs::copy_option::overwrite_if_exists, ec);
}
/*
if(ec)
{
return false;
}
return true;
*/
}