Hi, How to implement the ls "filename_[0-5][3-4]?" like class? The result I would like to store in the vector.
Currently I am using system() which is calling ls, but this is not portable under MS.
thanks, Arman.
Hi, How to implement the ls "filename_[0-5][3-4]?" like class? The result I would like to store in the vector.
Currently I am using system() which is calling ls, but this is not portable under MS.
thanks, Arman.
You can use boost::filesystem which has a portable way to retrieve files in a directory.
Then you can check the files against a regular expression with boost::regex for instance to only keep the ones that match your pattern.
The following program lists files in the current directory whose name matches the regular expression filename_[0-5][34]
:
#include <boost/filesystem.hpp>
#include <boost/regex.hpp> // also functional,iostream,iterator,string
namespace bfs = boost::filesystem;
struct match : public std::unary_function<bfs::directory_entry,bool> {
bool operator()(const bfs::directory_entry& d) const {
const std::string pat("filename_[0-5][34]");
std::string fn(d.filename());
return boost::regex_match(fn.begin(), fn.end(), boost::regex(pat));
}
};
int main(int argc, char* argv[])
{
transform_if(bfs::directory_iterator("."), bfs::directory_iterator(),
std::ostream_iterator<std::string>(std::cout, "\n"),
match(),
mem_fun_ref(&bfs::directory_entry::filename));
return 0;
}
I omitted the definition of transform_if()
for brevity. It isn't a standard function but it should be straightforward to implement.
The boost solution is portable, but not optimal on Windows. The reason is that it calls FindFirstFile("*.*")
and thus returns everything. Given the globbing pattern, it would be more efficient to call FindFirstFile("filename_?*.*")
. You'd still have to filter the results (using e.g. Boost::regex) but this would exclude many files that can't possibly match.
Also, using either method don't forget to filter out directories before doing the regex matching. The check whether an entry is a directory is quite cheap.