fnmatch.h - Linux


The fnmatch.h header file in Linux provides a collection of functions for performing wildcard pattern matching. It is used to determine if a string matches a wildcard pattern, where the pattern can contain wildcard characters like * (matches any number of characters) and ? (matches any single character).


#include <fnmatch.h>
int fnmatch(const char *pattern, const char *string, int flags);


| Flag | Description |
| FNM_NOESCAPE | Disable backslash () as an escape character |
| FNM_PATHNAME | Treat the string as a pathname |
| FNM_PERIOD | Match leading period (.) in filename |
| FNM_CASEFOLD | Perform case-insensitive matching |


Simple Matching:

const char *pattern = "*.txt";
const char *string = "file.txt";
if (fnmatch(pattern, string, 0) == 0) {
    printf("Match found!\n");

Matching with Flags:

const char *pattern = "x?y";
const char *string = "xyz";
if (fnmatch(pattern, string, FNM_CASEFOLD) == 0) {
    printf("Case-insensitive match found!\n");

Matching Pathnames:

const char *pattern = "/home/*/*";
const char *string = "/home/user/Documents/file.txt";
if (fnmatch(pattern, string, FNM_PATHNAME) == 0) {
    printf("Pathname match found!\n");

Common Issues

  • Invalid Patterns: Patterns with unbalanced parentheses or invalid characters can lead to runtime errors.
  • Case Sensitivity: By default, fnmatch is case-sensitive. Use FNM_CASEFOLD to perform case-insensitive matching.
  • Special Characters: Backslashes (\) are treated as escape characters by default. Use FNM_NOESCAPE to disable this behavior.


  • Shell Scripts: fnmatch can be used to perform wildcard matching in shell scripts to filter file listings, search for specific files, and more.
  • Programming Languages: fnmatch can be integrated into C and C++ programs to add wildcard matching functionality.

Related Commands

  • glob: Provides a similar wildcard matching functionality, but can also expand matched patterns.
  • regex: Provides regular expression matching capabilities, offering more advanced pattern matching options.