Skip to content

Instantly share code, notes, and snippets.

@ColleagueRiley
Last active July 13, 2021 20:32
Show Gist options
  • Save ColleagueRiley/64df8f28a57642f23b15c86a7fb4b034 to your computer and use it in GitHub Desktop.
Save ColleagueRiley/64df8f28a57642f23b15c86a7fb4b034 to your computer and use it in GitHub Desktop.
Simple glob headfile for easy glob use including a glob function and error handling.
#include <iostream>
#include <glob.h> // glob(), globfree()
#include <string.h> // memset()
#include <vector>
std::string globError;
int globReturn;
std::vector<std::string> ERRORglob(std::string error,glob_t glob_result){
globfree(&glob_result);
globError = "glob() failed with globReturn value " + std::to_string(globReturn) + error;
return {};
}
std::vector<std::string> glob(const std::string& pattern) {
// glob struct resides on the stack
glob_t glob_result;
memset(&glob_result, 0, sizeof(glob_result));
// do the glob operation
globReturn = glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result);
switch (globReturn){
case 1: return ERRORglob("; Glob ran out of memory",glob_result); break;
case 2: return ERRORglob("; Glob had an error while reading the folder",glob_result); break;
case 3: return ERRORglob("; Glob found no matches",glob_result); break;
default: globReturn=0; break;
}
// collect all the filenames into a std::list<std::string>
std::vector<std::string> filenames;
for(size_t i = 0; i < glob_result.gl_pathc; ++i) {
filenames.push_back(std::string(glob_result.gl_pathv[i]));
}
// cleanup
globfree(&glob_result);
// done
return filenames;
}
@ColleagueRiley
Copy link
Author

ColleagueRiley commented Jul 13, 2021

For debugging you can check globReturn for the glob's int error code or output globError for an error message.

Example:

#include <iostream>
#include <vector>
#include "glob.hpp"

int main(){
    //look for all .mp3 files in all found child directories in local directory "Music"
    std::vector<std::string> GL = glob("~/Music/*/*mp3");
    //if the error code isn't 0 (no error)
    if (globReturn){
        std::cout << globError; //output the error
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment