Many years ago, in my very first programming class in college, I was introduced to the concept of recursion. I loved it! I wanted to use it. For a number of years after that I was on the lookout for a practical application of recursion. But I eventually gave up.
Every recursive function that I wrote and every one that I ran across could be done better with a simple loop. Until now.
This function matches a pattern with an arbitrary number of
* and
? wildcard characters against a filename (without wildcards) and returns true or false.
I'm sure it could be written more efficiently without recursion, but I can't see a way to keep it simple without recursion. (In this application, speed is less important than simplicity.)
I'm pleased. I hope you are too.
Code:
int Match(const char *pattern, const char *filename)
{
if (NULL == pattern || NULL == filename)
{
return false;
}
// Match characters and '?' up to the first '*'
while (0 != *pattern && 0 != *filename && '*' != *pattern &&
(toupper(*pattern) == toupper(*filename) || '?' == *pattern))
{
pattern++;
filename++;
}
int match = (0 == *pattern && 0 == *filename);
// Use iterative recursion to match everything beyond the first '*'
if ('*' == *pattern++)
{
do {
match = Match(pattern, filename);
} while (!match && 0 != *filename++);
}
return match;
}