/*
 fn_compare.hpp
sdragonx 2015-02-25 14:32:54
*/ #ifndef FN_COMPARE_HPP_20150225143254 #define FN_COMPARE_HPP_20150225143254 #include <string> #define _CGL_BEGIN cgl{ #define _CGL_END } #define cstring std::basic_string _CGL_BEGIN /* 模糊查找文件名matching 例: bool b = fn_compare("abc.txt", "a?c.*"); sdragonx 2010-09-20 16:01 */ template<typename _char_t> bool fn_compare(const cstring<_char_t>& fname, const cstring<_char_t>& findstr) { //const static cstring<_char_t> mark = "*?"; _char_t mark[4] = { '*', '?' }; if(fname.empty() || findstr.empty()) { return false; } if(findstr.find_first_of(mark) == cstring<_char_t>::npos) { return fname.find(findstr) != cstring<_char_t>::npos; } else { size_t n = 0; for(size_t i = 0; i<findstr.size(); ) { if(findstr[i] == '*') { i = findstr.find_first_not_of(mark, i); if(i == cstring<_char_t>::npos){ return true; } n = fname.find(findstr[i], n); if(n == cstring<_char_t>::npos){ return false; } } else if(findstr[i] == '?') { ++n; ++i; } else { //while(mark.find(findstr[i]) == cstring<_char_t>::npos) while(findstr[i] != '*' && findstr[i] != '?') { if(!findstr[i]){ return true; } else if(fname[n++] != findstr[i++]){ return false; } } } } return !(n < fname.size()); } } _CGL_END #endif //FN_COMPARE_HPP_20150225143254

应用:

char* filename = "abc/a.txt";

bool n = fn_compare(filename, "abc/*.tx?");
n == yes

bool n = fn_compare(filename, "abc/*.bmp");
n == no

bool n = fn_compare(filename, "a?c/*.txt");
n == yes

文章发布于 2017-02-04 07:44:02 CSDN,现转博客园。