glob.h - Linux
Overview
glob.h is a header file that provides macros and functions for performing filename globbing in C programs. It allows you to expand wildcards (*
, ?
, []
, etc.) in file paths.
Syntax
#include <glob.h>
int glob(const char *pattern, int flags, int (*errfunc) (const char *, int), glob_t *pglob);
Options/Flags
| Flag | Description | Default |
| — | — | — |
| GLOB_ERR
| Specify an error occurred | N/A |
| GLOB_MARK
| Append a ‘/’ to directories | No |
| GLOB_NOCHECK
| Don’t check for file existence | No |
| GLOB_NOSORT
| Don’t sort the matching files | No |
| GLOB_TILDE
| Expand ‘~’ tilde characters | Yes |
Examples
Simple pattern matching:
#include <glob.h>
int main() {
glob_t result;
glob("*.c", 0, NULL, &result);
for (size_t i = 0; i < result.gl_pathc; i++) {
printf("%s\n", result.gl_pathv[i]);
}
return 0;
}
Advanced pattern matching with options:
#include <glob.h>
int main() {
glob_t result;
glob("*.{c,h}", GLOB_NOSORT | GLOB_NOCHECK, NULL, &result);
for (size_t i = 0; i < result.gl_pathc; i++) {
printf("%s\n", result.gl_pathv[i]);
}
return 0;
}
Common Issues
- Bad argument: Ensure the pattern string is valid and the flags are supported.
- No matches: The pattern may not match any files in the current directory. Check the pattern and ensure it is correct.
- Memory allocation failure: The glob function may fail if there is not enough memory to store the matching filenames.
Integration
Error handling: Provide a custom error function to handle any errors that occur while globbing.
Scripting: Use globbing in shell scripts or Python programs to expand wildcards and process multiple files.