// E05-DirectoryList.cpp -- list the files that match the given name pattern in a directory
//  usage: ./E05-DirectoryList [directory] [pattern]

// NOTE: when specifying star ('*') at command line enclose it in quotes, e.g. "*bin*"
//  this is because the shell (NT and Unix) does its magic on unquoted star characters


#include <Platform.h>
using namespace Platform;
using namespace Platform::Containers;


// MyFilter implements name pattern matching function "accept"
//----------------------------------------------------------------------------------------------------
struct MyFilter:
    Runtime::FileSystem::ListFilter
{
    // the pattern
    String pattern;

    // simple constructor
    MyFilter(const String& inPattern):
        pattern(inPattern)
    {}
    // filter method called by Runtime::FileSystem::list as it finds files in a directory
    Bool accept(const Path& path) const
    {
        return path.toString().regionMatches(pattern);
    }
};


// program entry point
//====================================================================================================
AppMain(args)
{
    String directory = appText(".");    // default: current directory
    String pattern = appText("*");      // default: match all

    // retrieve directory and pattern from command line (if given)
    if(args.size() > 1)
        directory = args[1];
    if(args.size() > 2)
        pattern = args[2];

    // list the specified directory using pattern as a name matching filter
    Array<Path> result = Runtime::FileSystem::list(Path(directory), MyFilter(pattern));

    // enumerate the result container printing collected filenames to StdOut
    for(Array<Path>::Enumerator en(result); en.hasNext();)
        Runtime::StdOut::println(en.next().toString());

    return 0;
}


/* EOF */