glob Example
posted under
C glob example
,
C program
,
C++ glob example
,
C++ program
,
glob example
,
glob sample
,
glob tutorial
,
linux
,
unix
by Anonymous
glob is a wonderful utility which retrieves the list of files from a specified location and returns the files which match the given regular expression.
The glob_t structure is used to store the result of the globbing operation. The globfree function is used to free the memory allocated for the structure after globbing.
The number of matches is stored in gl_pathc (Glob Path Count) field of glob_t.
Each match is stored in gl_pathv (Glob Path Value) field of glob_t.
I think its better to check if gl_pathc is greater than zero before invoking globfree, as otherwise it caused a segmentation fault on my system.
Type "man glob" at the console without the quotes to get a lot of detailed information.
#include <glob.h>
#include <string>
#include <vector>
using namespace std;
void getFiles( const string &pattern, vector<string> &fileList )
{
//Declare glob_t for storing the results of globbing
glob_t globbuf;
//Glob.. GLOB_TILDE tells the globber to expand "~" in the pattern to the home directory
glob( pattern.c_str(), GLOB_TILDE, NULL, &globbuf);
for( int i = 0; i < globbuf.gl_pathc; ++i )
fileList.push_back( globbuf.gl_pathv[i] );
//Free the globbuf structure
if( globbuf.gl_pathc > 0 )
globfree( &globbuf );
}

Comment Form under post in blogger/blogspot