1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
#include <iostream>
#include <fstream>
#include <regex>
#include <filesystem>
void replace_all( std::string& source, char replace, const std::string& replacement )
{
unsigned pos = 0 ;
while ( pos < source.length() && std::string::npos != (pos = source.find(replace, pos)) )
{
source.replace(pos, 1, replacement) ;
pos += replacement.length() ;
}
}
std::string to_regex_expression(const std::string& path)
{
std::string expression("^" + path) ;
replace_all(expression, '.', "\\.") ;
replace_all(expression, '*', ".*") ;
replace_all(expression, '?', "(.{1,1})") ;
return expression ;
}
namespace fs = std::tr2::sys ;
std::vector<fs::path> generate_paths(char const* pattern)
{
std::vector<fs::path> results ;
if ( std::string::npos == std::string(pattern).find_first_of("*?") )
{
if ( fs::exists(fs::path(pattern)) )
results.emplace_back(pattern) ;
return results ;
}
std::regex expr(to_regex_expression(pattern), std::regex_constants::icase) ;
for ( auto it = fs::directory_iterator(".") ; it != fs::directory_iterator() ; ++it )
{
if (std::regex_match(it->path().filename(), expr))
if ( fs::is_regular_file(it->path()) )
results.push_back(it->path()) ;
}
return results ;
}
template <typename T>
void print( const std::vector<T>&v )
{
for ( auto & path : v )
std::cout << path << '\n' ;
}
int main( int argc, char * argv[])
{
if ( argc > 1 )
{
std::vector<fs::path> files = generate_paths(argv[1]) ;
print(files) ;
}
}
|