Thread: filename pattern matching

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057

    Lightbulb filename pattern matching

    Here's a function that matches a filter (like *.c) to a filename (like hippo.c).

    Code:
    int match(char *f, char *s) {
        char *t;
    
        while(1) {
            if(*f == '?' || *s == '?') ;
            else if(*f == '*') {
                t = s;
                while(1) {
                    if(match(f+1, t)) return 1;
                    if(!*t++) break;
                }
    
                return 0;
            }
            else if(*s == '*') {
                t = f;
                while(1) {
                    if(match(s+1, t)) return 1;
                    if(!*t++) break;
                }
    
                return 0;
            }
            else if(*f != *s) return 0;
    
            if(!*s || !*f) break;
            s++, f++;
        }
    
        return *f || *s ? 0 : 1;
    }
    It returns 1 if there's a match, 0 otherwise.

    There's nothing wrong with it (as far as I can see), I was just wondering how it could be improved. It's a little too slow for me.

    Before anyone points it out, the * matching could be removed from one of the arguments.
    Last edited by dwks; 07-12-2005 at 04:47 PM.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 06-01-2009, 07:54 PM
  2. Pattern matching
    By GSLR in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 11-06-2003, 07:17 AM
  3. Going out of scope
    By nickname_changed in forum C++ Programming
    Replies: 9
    Last Post: 10-12-2003, 06:27 PM
  4. pattern matching
    By ahahplz in forum C Programming
    Replies: 5
    Last Post: 02-07-2003, 07:15 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM