#include<boost/optional.hpp>
#include<boost/filesystem.hpp>
#include<boost/filesystem/fstream.hpp>
#include<boost/optional.hpp>
#include<boost/xpressive/xpressive_dynamic.hpp>
#include<boost/algorithm/string.hpp>
#include<string>
#include<iostream>
using namespace std;
using namespace boost;
using namespace boost::filesystem;
using namespace boost::xpressive;
typedef recursive_directory_iterator rd_iterator;
//判断特定目录下是否有指定文件
optional<path> find_file(const path& dir, const string& filename) {
typedef optional<path> result_type;
if (!exists(dir) || !is_directory(dir)) {
return result_type();
}
rd_iterator end;
for (rd_iterator pos(dir); pos != end; ++pos) {
if (!is_directory(*pos) && pos->path().filename() == filename)
{
return result_type(pos->path());
}
}
return result_type();
}
//实现模糊查找文件
void find_files(const path& dir, const string& filename, vector<path>& v) {
static xpressive::sregex_compiler rc;
if (!rc[filename].regex_id())
{
string str = replace_all_copy(
replace_all_copy(filename, ".", "\\."),
"*", ".*"
);
rc[filename] = rc.compile(str);
}
typedef vector<path> result_type;
if (!exists(dir) || !is_directory(dir)) {
return;
}
rd_iterator end;
for (rd_iterator pos(dir); pos != end; ++pos) {
if (!is_directory(*pos) &&
regex_match(pos->path().filename(), rc[filename])) {
v.push_back(pos->path());
}
}
}
int main()
{
optional<path> r = find_file("G:/Reading/papers", "1707.06742.pdf");
if (r) {
cout << *r << endl;
}
else {
cout << "file not found" << endl;
}
return 0;
}
Boost filesystem库操作文件系统
最新推荐文章于 2025-02-14 19:20:12 发布