C++ 实现文件的复制和移动

想实现一个文件的复制和移动的函数,来处理文件,可惜电脑上面没有安装Matlab,就想用 C++ 来实现这个功能。分别使用 C 里面的 rename 函数和 C++ 中的 stream 来实现。rename 就是简单的修改文件名,如果文件路径包含在文件名中了,那么就可以修改此路径实现文件移动的功能。 stream 的方式就是先读入文件,再写入新文件,可以设置是否保留源文件。^_^

#include <cstdio>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>

struct FileMover
{
    virtual bool move(const std::string& src, const std::string& dst) const = 0;
    bool move(const std::vector<std::string>& src, const std::vector<std::string>& dst) const;
    FileMover(){}
    virtual ~FileMover(){}
};
bool FileMover::move(const std::vector<std::string>& src, const std::vector<std::string>& dst) const{
    if (src.size() != dst.size()){
        std::cerr << "src and dst files number not equal" << std::endl;
        return false;
    }
    bool ret = true;
    for (int i = 0; i < src.size(); ++i)
        ret &= move(src[i].c_str(), dst[i].c_str());
    return ret;
}

// method 1
// C 
// move file by rename. 
// This is an operation performed directly on a file;
// No streams are involved in the operation.
struct RenameMover :public FileMover{
    bool move(const std::string& src, const std::string& dst) const override;
};
bool RenameMover::move(const std::string& src, const std::string& dst) const{
    //int rename(const char * oldname, const char * newname);
    if (0 == rename(src.c_str(), dst.c_str()))
        return true;
    perror("Error renaming file");
    return false;
}


// method 2
// C++
// move flle by read and write using std::ios::stream.
struct StreamMover :public FileMover{
    StreamMover(bool keep=false) :keep_src(keep){}
    ~StreamMover(){}
    bool keep_src;
    bool move(const std::string& src, const std::string& dst) const override;
};
bool StreamMover::move(const std::string& src, const std::string& dst) const{
    std::ifstream ifs(src, std::ios::binary);
    std::ofstream ofs(dst, std::ios::binary);
    if (!ifs.is_open()){
        std::cout << "open src file fail: " + src << std::endl;
        return false;
    }
    ofs << ifs.rdbuf();
    ifs.close(); 
    ofs.close();
    if (!keep_src && 0 != remove(src.c_str())){
        std::cerr << "remove src file fail: " + src << std::endl;
    }
    return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值