您的位置:首页 > 编程语言 > C语言/C++

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

2017-02-26 19:44 162 查看
想实现一个文件的复制和移动的函数,来处理文件,可惜电脑上面没有安装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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++