文件操作之复制

需要做一个软件更新的功能,软件更新过程中需要考虑一些异常,其中关于固件备份(防止升级失败)的过程,不甘心用system((char *)cmd)的方式,采用文件打开读写关闭的方式实现。

/**
     * @brief 复制文件夹
     * @param sourcePath 源文件夹
     * @param destPath 目的文件夹
     */
    void copyfolder(std::string sourcePath, std::string destPath)
    {
        struct dirent *filename = NULL;
        std::string path = sourcePath;
        opendir(destPath.c_str());
        if (sourcePath.back() != '/')
        {
            sourcePath += "/";
        }
        if (destPath.back() != '/')
        {
            destPath += "/";
        }

        DIR *dp = opendir(path.c_str());
        if (dp == NULL)
            return;
        while (filename = readdir(dp))
        {
            std::string fileSourcePath = sourcePath;
            std::string fileDestPath = destPath;
            fileSourcePath += filename->d_name;
            fileDestPath += filename->d_name;
            if (is_dir(fileSourcePath.c_str()))
            {
                if (strncmp(filename->d_name, ".", 1) && strncmp(filename->d_name, "..", 2))
                    copyfolder(fileSourcePath, fileDestPath);
            }
            else
            {
                copyfile(fileSourcePath, fileDestPath);
            }
        }
    }

    /**
     * @brief 复制文件
     * @param sourcePath 源文件
     * @param destPath 目的文件
     */
    void copyfile(std::string sourcePath, std::string destPath)
    {
        int pIn, pOut;
        char buff[FILE_CACHE] = {0};
        if ((pIn = open(sourcePath.data(), O_RDONLY)) == -1)
            return;
        struct stat sourceStat;
        stat(sourcePath.data(), &sourceStat);
        int flag = destPath.find_last_of("/");
        std::string destFile = destPath.substr(0, flag);
        is_file_exist(destFile, true);

        if (S_IXUSR & sourceStat.st_mode)
            pOut = open(destPath.data(), O_CREAT | O_RDWR | O_TRUNC, 0775);
        pOut = open(destPath.data(), O_CREAT | O_RDWR | O_TRUNC, 0444);
        if (pOut == -1)
            return;
        int len = 0;
        int temp_source_size = sourceStat.st_size;
        int temp_cnt = 0;
        while (temp_source_size > 0)
        {
            len = 0;
            len = read(pIn, buff, FILE_CACHE);
            write(pOut, buff, len);
            temp_source_size -= len;
            temp_cnt += len;
        }

        close(pOut);
        close(pIn);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值