![]() |
![]() |
![]() |
Find paths matching a pattern
#include <glob.h> int glob( const char* pattern, int flags, int (*errfunc)( const char*, int ), glob_t* pglob );
libc
The glob() function finds pathnames matching the given pattern by matching:
In order to have access to a pathname, glob() must have search permission on every component of the path except the last, and read permission on each directory of every filename component of pattern that contains any of the special characters (*, ?, [ and ]).
The glob_t structure contains at least the following members:
Member | Description |
---|---|
size_t gl_pathc | The number of pathnames matched by pattern. |
char** gl_pathv | NULL-terminated array of pointers to the pathnames matched by pattern. |
size_t gl_offs | The number of pointers to reserve at the beginning of gl_pathv. |
The errfunc argument is a pointer to an error-handler function with this prototype:
int errfunc( const char* epath, int eerno );
The errfunc function is called when glob() encounters a directory it cannot open or read. epath will be a pointer to the path that failed, and eerno will be the value of errno from the failure. eerno can be set to any of the values returned by opendir(), readdir(), or stat(). The errfunc function should return 0 if glob() should continue, or nonzero if glob() should stop searching.
You can set errfunc to NULL to ignore these types of errors.
The flags argument can be set to any combination of the following bit flags:
You must create the glob_t structure (pointed to by pglob) before the call to glob(). The glob() function will allocate storage as needed for the gl_pathv array. Use globfree() to free the space allocated by a previous call to glob().
Zero for success, or an error value.
This simple example attempts to find all of the .c files in the current directory and print them in the order the filesystem found them.
#include <unistd.h> #include <stdio.h> #include <glob.h> int main( void ) { glob_t paths; int retval; paths.gl_pathc = 0; paths.gl_pathv = NULL; paths.gl_offs = 0; retval = glob( "*.c", GLOB_NOCHECK | GLOB_NOSORT, NULL, &paths ); if( retval == 0 ) { int idx; for( idx = 0; idx < paths.gl_pathc; idx++ ) { printf( "[%d]: %s\n", idx, paths.gl_pathv[idx] ); } globfree( &paths ); } else { puts( "glob() failed" ); } return 0; }
Safety: | |
---|---|
Cancellation point | Yes |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |
Don't change the values in pglob between calling glob() and globfree().
globfree(), wordexp(), wordfree()
![]() |
![]() |
![]() |