Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple glob in C++ on unix system?

Tags:

c++

unix

glob

I want to retrieve all the matching paths following this pattern in a vector<string>:

"/some/path/img*.png" 

How can I simply do that ?

like image 852
Benjamin Crouzier Avatar asked Dec 06 '11 14:12

Benjamin Crouzier


People also ask

What is a Unix glob?

In computer programming, glob (/ɡlɑːb/) patterns specify sets of filenames with wildcard characters. For example, the Unix Bash shell command mv *. txt textfiles/ moves ( mv ) all files with names ending in .

What is glob C?

In your C code, the glob() function helps evaluate filename input that includes the global wildcard characters. Here is the man page format for the glob() function, which requires that the glob.

Why is it called glob?

The glob command, short for global, originates in the earliest versions of Bell Labs' Unix.

What is a glob file?

A glob is a term used to define patterns for matching file and directory names based on wildcards. Globbing is the act of defining one or more glob patterns, and yielding files from either inclusive or exclusive matches.


1 Answers

I have that in my gist. I created a stl wrapper around glob so that it returns vector of string and take care of freeing glob result. Not exactly very efficient but this code is a little more readable and some would say easier to use.

#include <glob.h> // glob(), globfree() #include <string.h> // memset() #include <vector> #include <stdexcept> #include <string> #include <sstream>  std::vector<std::string> glob(const std::string& pattern) {     using namespace std;      // glob struct resides on the stack     glob_t glob_result;     memset(&glob_result, 0, sizeof(glob_result));      // do the glob operation     int return_value = glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result);     if(return_value != 0) {         globfree(&glob_result);         stringstream ss;         ss << "glob() failed with return_value " << return_value << endl;         throw std::runtime_error(ss.str());     }      // collect all the filenames into a std::list<std::string>     vector<string> filenames;     for(size_t i = 0; i < glob_result.gl_pathc; ++i) {         filenames.push_back(string(glob_result.gl_pathv[i]));     }      // cleanup     globfree(&glob_result);      // done     return filenames; } 
like image 90
Piti Ongmongkolkul Avatar answered Oct 02 '22 12:10

Piti Ongmongkolkul