Thursday, January 14, 2010

ls using boost

Want to use boost and get list of files matching a mask. The same list you would obtain running ls in the command prompt?

The idea is to have something like this:


BOOST_FOREACH( const std::string& fname, ls( "./*.cpp" ))
std::cout << fname << std::endl ;


So here is the solution. One function and one helper function (to_regex_copy()):


std::string to_regex_copy( std::string mask )
{
std::string rv = boost::regex_replace( boost::regex_replace( boost::regex_replace( mask, boost::regex( "\\." ), "\\\\." ), boost::regex( "\\?" ), "\\." ), boost::regex( "\\*" ), "\\.*" ) ;
return rv ;
}

std::vector< std::string > ls( const char* pcszMask )
{
namespace fs = boost::filesystem ;
boost::filesystem::path path ;
boost::regex mask ;
if ( fs::is_directory( pcszMask ))
{
path = pcszMask ;
mask = ".*" ;
}
else
{
path = fs::path( pcszMask ).remove_filename() ;
mask = to_regex_copy( fs::path( pcszMask ).filename()) ;
}

std::vector< std::string > rv ;
try
{
for ( fs::directory_iterator p(path), e; p!=e; ++p)
{
if ( boost::regex_match( p->filename(), mask ))
rv.push_back( p->filename()) ;
}
}
catch( ... )
{
}

return rv ;
}

No comments: