Section 23.1. Globbing Arbitrary Strings

   


23.1. Globbing Arbitrary Strings

Chapter 14 explains how to glob file names using the glob() function, but people used to globbing capabilities sometimes wish to apply them to other sorts of strings. The fnmatch() function allows you to apply globbing rules to arbitrary strings:

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


The pattern is a standard glob expression with four special characters, modified by the flags argument:

*

Matches any string, including an empty one.

?

Matches exactly one character, any character.

[

Starts a list of characters to match, or, if the next character is ^, a list of characters not to match. The whole list matches, or does not match, a single character. The list is terminated by a ].

\

Causes the next character to be interpreted literally instead of as a special character.


The flags argument affects some details of the glob, and is mostly there to be useful for globbing against file names. If you are not globbing file names, you probably want to set flags to 0.

 FNM_NOESCAPE 


Treat \ as an ordinary character, not a special character.

 FNM_PATHNAME 


Do not match / characters in string with a *, ?, or even a [/] sequence in pattern; match it only with a literal, nonspecial /.

 FNM_PERIOD 


A leading . character in pattern matches a . character in string only if it is the first character in string or if FNM_PATHNAME is set and the . character in string directly follows a \.

fnmatch() returns zero if the pattern matches the string, FNM_NOMATCH if the pattern does not match the string, or some other unspecified value if an error occurs.

An example of using fnmatch() is provided in the example program on pages 315-317 in Chapter 14, where it is used as part of a simple reimplementation of the find command.


       
    top
     


    Linux Application Development
    Linux Application Development (paperback) (2nd Edition)
    ISBN: 0321563220
    EAN: 2147483647
    Year: 2003
    Pages: 168

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net