Commit d73dd2ea750e4d3a9c3f089984b7086ca18147e9

Authored by Jordi Inglada
1 parent 5bdec549
Exists in master

List files in directory

Showing 1 changed file with 23 additions and 0 deletions   Show diff stats
include/cbutils.h
... ... @@ -26,6 +26,8 @@
26 26 #include <cassert>
27 27 #include <chrono>
28 28 #include <iomanip>
  29 +#include <experimental/filesystem>
  30 +#include <regex>
29 31 namespace cbutils
30 32 {
31 33 // ----------------- String manipulation ---------------------------------------
... ... @@ -69,6 +71,7 @@ std::string call(const std::string&amp; command)
69 71 // ----------------- File IO ---------------------------------------------------
70 72 namespace file
71 73 {
  74 +namespace fs = std::experimental::filesystem;
72 75 //Reads a text file and returns a vector of lines
73 76 std::vector<std::string> read_lines(const std::string& fname)
74 77 {
... ... @@ -100,6 +103,26 @@ std::size_t count_columns(const std::string&amp; fname,
100 103 }
101 104 return 0;
102 105 }
  106 +// List the files in a directory eventually matching a pattern
  107 +// needs to link with -lstdc++fs
  108 +std::vector<std::string> list_files(const std::string& dir,
  109 + const std::string& pattern = ".*")
  110 +{
  111 + std::regex regex_pattern(pattern);
  112 + namespace fs = std::experimental::filesystem;
  113 + std::vector<std::string> result;
  114 + for(auto& p: fs::directory_iterator(dir))
  115 + {
  116 + std::stringstream fname;
  117 + fname << p;
  118 + if(std::regex_search(fname.str(), regex_pattern))
  119 + {
  120 + result.emplace_back(fname.str());
  121 + }
  122 + }
  123 +
  124 + return result;
  125 +}
103 126 }//end ns file
104 127 // ----------------- Sequence manipulation -------------------------------------
105 128 namespace seq
... ...