glob, globfree - generate pathnames matching a pattern
#include <glob.h>
int glob(const char *restrictpattern, intflags,
int(*errfunc)(const char *epath, inteerrno),
glob_t *restrictpglob);
void globfree(glob_t *pglob);
Theglob() function is a pathname generator that shall implement the rules defined in XCUPattern Matching Notation, with optional support for rule 3 in XCUPatterns Used for Filename Expansion.
The structure typeglob_t is defined in<glob.h> and includes at leastthe following members:
Member Type
Member Name
Description
size_t
gl_pathc
Count of paths matched bypattern.
char **
gl_pathv
Pointer to a list of matched pathnames.
size_t
gl_offs
Slots to reserve at the beginning ofgl_pathv.
The argumentpattern is a pointer to a pathname pattern to be expanded. Theglob() function shall match allaccessible pathnames against this pattern and develop a list of all pathnames that match. In order to have access to a pathname,glob() requires search permission on every component of a path except the last, and read permission on each directory of anyfilename component ofpattern that contains any of the following special characters:'*','?', and'['.
Theglob() function shall store the number of matched pathnames intopglob->gl_pathc and a pointer to alist of pointers to pathnames intopglob->gl_pathv. The pathnames shall be in sort order as defined by the currentsetting of theLC_COLLATE category; see XBDLC_COLLATE. Thefirst pointer after the last pathname shall be a null pointer. If the pattern does not match any pathnames, the returned number ofmatched paths is set to 0, and the contents ofpglob->gl_pathv are implementation-defined.
It is the caller's responsibility to create the structure pointed to bypglob. Theglob() function shall allocateother space as needed, including the memory pointed to bygl_pathv. Theglobfree() function shall free any spaceassociated withpglob from a previous call toglob().
Theflags argument is used to control the behavior ofglob(). The value offlags is a bitwise-inclusive ORof zero or more of the following constants, which are defined in<glob.h>:
- GLOB_APPEND
- Append pathnames generated to the ones from a previous call toglob().
- GLOB_DOOFFS
- Make use ofpglob->gl_offs. If this flag is set,pglob->gl_offs is used to specify how manynull pointers to add to the beginning ofpglob->gl_pathv. In other words,pglob->gl_pathv shallpoint topglob->gl_offs null pointers, followed bypglob->gl_pathc pathname pointers, followed bya null pointer.
- GLOB_ERR
- Causeglob() to return when it encounters a directory that it cannot open or read. Ordinarily,glob() continuesto find matches.
- GLOB_MARK
- Each pathname that is a directory that matchespattern shall have a <slash> appended.
- GLOB_NOCHECK
- Supports rule 3 in XCUPatterns Used for Filename Expansion. Ifpattern does not match any pathname, thenglob() shall return a list consisting of onlypattern, and thenumber of matched pathnames is 1.
- GLOB_NOESCAPE
- Disable backslash escaping.
- GLOB_NOSORT
- Ordinarily,glob() sorts the matching pathnames according to the current setting of theLC_COLLATE category; seeXBDLC_COLLATE. When this flag is used, the order of pathnamesreturned is unspecified.
The GLOB_APPEND flag can be used to append a new set of pathnames to those found in a previous call toglob(). Thefollowing rules apply to applications when two or more calls toglob() are made with the same value ofpglob andwithout intervening calls toglobfree():
The first such call shall not set GLOB_APPEND. All subsequent calls shall set it.
All the calls shall set GLOB_DOOFFS, or all shall not set it.
After the second call,pglob->gl_pathv points to a list containing the following:
Zero or more null pointers, as specified by GLOB_DOOFFS andpglob->gl_offs.
Pointers to the pathnames that were in thepglob->gl_pathv list before the call, in the same order asbefore.
Pointers to the new pathnames generated by the second call, in the specified order.
The count returned inpglob->gl_pathc shall be the total number of pathnames from the two calls.
The application can change any of the fields after a call toglob(). If it does, the application shall reset them to theoriginal value before a subsequent call, using the samepglob value, toglobfree() orglob() with theGLOB_APPEND flag.
If, during the search, a directory is encountered that cannot be opened or read anderrfunc is not a null pointer,glob() calls (*errfunc()) with two arguments:
Theepath argument is a pointer to the path that failed.
Theeerrno argument is the value oferrno from the failure, as set byopendir(),readdir(), orstat(). (Other values may be used to report other errors not explicitly documented for thosefunctions.)
If (*errfunc()) is called and returns non-zero, or if the GLOB_ERR flag is set inflags,glob() shall stopthe scan and return GLOB_ABORTED after settinggl_pathc andgl_pathv inpglob to reflect the paths alreadyscanned. If GLOB_ERR is not set and eithererrfunc is a null pointer or (*errfunc()) returns 0, the error shall beignored.
Theglob() function shall not fail because of large files.
Upon successful completion,glob() shall return 0. The argumentpglob->gl_pathc shall return the numberof matched pathnames and the argumentpglob->gl_pathv shall contain a pointer to a null-terminated list of matchedand sorted pathnames. However, ifpglob->gl_pathc is 0, the content ofpglob->gl_pathv isundefined.
Theglobfree() function shall not return a value.
Ifglob() terminates due to an error, it shall return one of the non-zero constants defined in<glob.h>. The argumentspglob->gl_pathc andpglob->gl_pathv are still set as defined above.
Theglob() function shall fail and return the corresponding value if:
- GLOB_ABORTED
- The scan was stopped because GLOB_ERR was set or (*errfunc()) returned non-zero.
- GLOB_NOMATCH
- The pattern does not match any existing pathname, and GLOB_NOCHECK was not set in flags.
- GLOB_NOSPACE
- An attempt to allocate memory failed.
One use of the GLOB_DOOFFS flag is by applications that build an argument list for use withexecv(),execve(), orexecvp(). Suppose, for example, that an application wants to do the equivalent of:
ls -l *.cbut for some reason:
system("ls -l *.c")is not acceptable. The application could obtain approximately the same result using the sequence:
globbuf.gl_offs = 2;glob("*.c", GLOB_DOOFFS, NULL, &globbuf);globbuf.gl_pathv[0] = "ls";globbuf.gl_pathv[1] = "-l";execvp("ls", &globbuf.gl_pathv[0]);Using the same example:
ls -l *.c *.hcould be approximately simulated using GLOB_APPEND as follows:
globbuf.gl_offs = 2;glob("*.c", GLOB_DOOFFS, NULL, &globbuf);glob("*.h", GLOB_DOOFFS|GLOB_APPEND, NULL, &globbuf);...
This function is not provided for the purpose of enabling utilities to perform pathname expansion on their arguments, as thisoperation is performed by the shell, and utilities are explicitly not expected to redo this. Instead, it is provided forapplications that need to do pathname expansion on strings obtained from other sources, such as a pattern typed by a user or readfrom a file.
If a utility needs to see if a pathname matches a given pattern, it can usefnmatch().
Note thatgl_pathc andgl_pathv have meaning even ifglob() fails. This allowsglob() to reportpartial results in the event of an error. However, ifgl_pathc is 0,gl_pathv is unspecified even ifglob()did not return an error.
The GLOB_NOCHECK option could be used when an application wants to expand a pathname if wildcards are specified, but wants totreat the pattern as just a string otherwise. Thesh utility might use this foroption-arguments, for example.
The new pathnames generated by a subsequent call with GLOB_APPEND are not sorted together with the previous pathnames. Thismirrors the way that the shell handles pathname expansion when multiple expansions are done on a command line.
Applications that need tilde and parameter expansion should usewordexp().
It was claimed that the GLOB_DOOFFS flag is unnecessary because it could be simulated using:
new = (char **)malloc((n + pglob->gl_pathc + 1) * sizeof(char *));(void) memcpy(new+n, pglob->gl_pathv, pglob->gl_pathc * sizeof(char *));(void) memset(new, 0, n * sizeof(char *));free(pglob->gl_pathv);pglob->gl_pathv = new;However, this assumes that the memory pointed to bygl_pathv is a block that was separately created usingmalloc(). This is not necessarily the case. An application should make no assumptions abouthow the memory referenced by fields inpglob was allocated. It might have been obtained frommalloc() in a large chunk and then carved up withinglob(), or it might have beencreated using a different memory allocator. It is not the intent of the standard developers to specify or imply how the memory usedbyglob() is managed.
The GLOB_APPEND flag would be used when an application wants to expand several different patterns into a single list.
None.
First released in Issue 4. Derived from the ISO POSIX-2 standard.
Moved from POSIX2 C-language Binding to BASE.
The normative text is updated to avoid use of the term "must" for application requirements.
Therestrict keyword is added to theglob() prototype for alignment with the ISO/IEC 9899:1999 standard.
return to top of page