Skip to content

Instantly share code, notes, and snippets.

@shawwn
Created June 15, 2023 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shawwn/2de8072226dcf619d51763d9af2cc58a to your computer and use it in GitHub Desktop.
Save shawwn/2de8072226dcf619d51763d9af2cc58a to your computer and use it in GitHub Desktop.
A simple glob function that returns a vector of strings for POSIX
#include <glob.h>
#include <vector>
#include <string>
namespace util
{
std::vector<std::string> glob(const std::string& pattern) {
glob_t glob_result = {0}; // zero initialize
// do the glob operation
int return_value = ::glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result);
if(return_value != 0) throw std::runtime_error(std::strerror(errno));
// collect all the filenames into a std::vector<std::string>
// using the vector constructor that takes two iterators
std::vector<std::string> filenames(
glob_result.gl_pathv, glob_result.gl_pathv + glob_result.gl_pathc);
// cleanup
globfree(&glob_result);
// done
return filenames;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment