C++文件与文件夹操作(3)--文件与文件夹复制

(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; 
*/
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值