C++ 目录遍历与文件拷贝

基于Boost库,相关头文件

#include 
#include 
#include 
#include 
using namespace boost::xpressive; //正则表达式
using namespace boost::filesystem;
using namespace boost;

使用时注意异常处理!!

目录遍历:返回所有符合要求的目录和文件

  • 支持模糊查询
  • 支持递归遍历
vector<path>
find_files(const string& dir, const string& filename) {
	// flyweight(享元模式)
	static sregex_compiler rc;
	if (!rc[filename].regex_id()) {
		string str = replace_all_copy(replace_all_copy(filename, ".", "\\."), "*", ".*");
		rc[filename] = rc.compile(str);
	}
	vector<path> v;
	if (!exists(dir) || !is_directory(dir)) {
		return v;
	}
	using rd_iterator = recursive_directory_iterator;
	rd_iterator end;
	for (rd_iterator pos(dir); pos != end; ++pos) {
		if (regex_match(pos->path().filename().string(), rc[filename])) {
			v.push_back(pos->path());
		}
	}
	return v;
}

文件拷贝:基于目录遍历

  • 支持进度条显示
  • 支持文件名模糊筛选
  • 支持空目录拷贝
size_t
copy_files(const string& from_dir, const string& to_dir, const string& filename = "*") {
	if (!is_directory(from_dir)) {
		cout << from_dir << " is not a dir." << endl;
		return 0;
	}
	cout << "prepare for copy, please wait..." << endl;
	auto v = find_files(from_dir, filename);
	if (v.empty()) {
		cout << "0 file copyed." << endl;
		return 0;
	}
	cout << "begin copying files ..." << endl;
	progress_display pd(v.size());
	for (auto& p : v) {
		path tmp = to_dir;
		tmp /= p.string().substr(from_dir.length());
		if (is_directory(p)) {
			if (!exists(tmp)) {
				create_directories(tmp);
			}
		}
		else {
			
			path parent_dir = tmp.parent_path();
			if (!exists(parent_dir)) {
				create_directories(parent_dir);
			}
			copy_file(p, tmp, copy_option::overwrite_if_exists);
		}
		++pd;
	}
	cout << v.size() << " files copyed." << endl;
	return v.size();
}

C++ 目录遍历与文件拷贝_第1张图片

你可能感兴趣的:(C++)