#include <iostream>
#include <string>
#include <ftw.h>
#include <fts.h>
template <typename T>
void walk_dir(std::string const& fpath, T&& function)
{
char const* filepath[] = { fpath.c_str(), nullptr };
auto* tree = fts_open(const_cast<char *const *>(filepath), FTS_LOGICAL | FTS_NOSTAT, [](auto const**, auto const**) { return 0; });
if (tree == nullptr)
{
std::cerr << "Error opening tree\n";
throw std::runtime_error("fts_open failure");
}
FTSENT* s;
while ((s = fts_read(tree)))
{
switch (s->fts_info)
{
case FTS_DNR: /* Cannot read directory */
case FTS_ERR: /* Miscellaneous error */
case FTS_NS: /* stat() error Show error, then continue to next files. */
std::cerr << "Error on " << s->fts_path << "\n";
continue;
case FTS_DP: /* Ignore post-order visit to directory. */
continue;
}
function(s);
}
fts_close(tree);
}
int main()
{
walk_dir(".", [](auto&&) {});
}
std::vector<std::string> find_paths(const std::string& root, const std::string& regexStr)
{
std::vector<std::string> paths;
std::regex r(regexStr);
walk_dir(root, [&paths, &r](auto* f) {
if (std::regex_match(f->fts_path, r))
{
paths.push_back(f->fts_path);
}
});
return paths;
}
int main(int ac, char** av)
{
if (ac < 3) return 1;
for (auto const& path : ::find_paths(av[1], av[2]))
{
std::cout << path << '\n';
}
}
#include <iostream>
#include <sstream>
#include <variant>
template<class T> struct always_false : std::false_type {};
struct NullType {};
template <typename T>
using Maybe = std::variant<NullType, T>;
Maybe<int> get_int()
{
Maybe<int> m; // Here, m is a NullType
std::string input;
int i;
std::getline(std::cin, input);
std::stringstream ss(input);
if (ss >> i)
m = i; // If we get here, m becomes an int
return m;
}
int main()
{
auto m = get_int();
std::visit([](auto&& m) {
using T = std::remove_cv_t<std::remove_reference_t<decltype(m)>>;
if constexpr (std::is_same_v<T, int>) { printf("got an int\n"); }
// Comment the `else if` below to get an error from the static_assert
else if constexpr (std::is_same_v<T, NullType>) { printf("got nothing\n"); }
else static_assert(always_false<T>::value, "non-exhaustive visitor!");
// This is useful because we can change the variant and get errors wherever we have to update our handling code
}, m);
}