基於Boost庫,相關頭文件
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/xpressive/xpressive_dynamic.hpp>
#include <boost/progress.hpp>
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();
}