CPP-Shooter's Life
정규표현식으로 특정 확장자의 파일을 모두 찾기 본문
** 출처 : http://rextester.com/SAY51073 **
#include <iostream>
#include <string>
#include <vector>
#include <experimental/filesystem>
#include <regex>
#include <type_traits>
namespace fs = std::experimental::filesystem ;
// list of paths of all files under the directory 'dir' when the extenstion matches the regex
// file_list<true> searches recursively into sub-directories; file_list<false> searches only the specified directory
template < bool RECURSIVE > std::vector<fs::path> file_list( fs::path dir, std::regex ext_pattern )
{
std::vector<fs::path> result ;
using iterator = std::conditional< RECURSIVE,
fs::recursive_directory_iterator, fs::directory_iterator >::type ;
const iterator end ;
for( iterator iter { dir } ; iter != end ; ++iter )
{
const std::string extension = iter->path().extension().string() ;
if( fs::is_regular_file(*iter) && std::regex_match( extension, ext_pattern ) ) result.push_back( *iter ) ;
}
return result ;
}
// literal '.' followed by one of "cpp", "cc", "cxx", "h", "hh", "hpp" or "hxx"
// note: ?: indicates that it is a non-capturing group
static const std::regex cpp_files( "\\.(?:cpp|cc|cxx|h|hh|hpp|hxx)" ) ;
// non-recursive scan for c++ files: if dir is omitted, current directory is scanned
std::vector<fs::path> scan_cpp_files( fs::path dir = "." ) { return file_list<false>( dir, cpp_files ) ; }
// recursive scan for c++ files: if dir is omitted, current directory is scanned
std::vector<fs::path> rscan_cpp_files( fs::path dir = "." ) { return file_list<true>( dir, cpp_files ) ; }
int main()
{
const fs::path win_dir = "C:/Windows/" ; // adjust as required
// print files with extension ".log" or ".ini" in the directory win_dir (non-recursive)
for( const auto& file_path : file_list<false>( win_dir, std::regex( "\\.(?:log|ini)" ) ) )
std::cout << file_path << '\n' ;
std::cout << "\n----------------------------------------------\n" ;
// print files with extension ".log" in the directory "C:/Windows/Logs" (recursive)
for( const auto& file_path : file_list<true>( win_dir/"Logs", std::regex( "\\.(?:log|ini)" ) ) )
std::cout << file_path << '\n' ;
std::cout << "\n----------------------------------------------\n" ;
// print all c++ files the current directory (non-recursive)
for( const auto& file_path : scan_cpp_files() )
std::cout << file_path << '\n' ;
std::cout << "\n----------------------------------------------\n" ;
const fs::path vc_crt_src = "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/crt/src" ;
// print all c++ files in the directory vc_crt_src (recursive)
for( const auto& file_path : rscan_cpp_files(vc_crt_src) )
std::cout << file_path.parent_path().stem() / file_path.filename() << '\n' ;
std::cout << "\n----------------------------------------------\n" ;
}
'Programming > C++' 카테고리의 다른 글
Directory_iterator (0) | 2019.01.14 |
---|