harper harper - 1 year ago 102
C Question

file name matching with wildcard

I need to implement something like my own file system. One operation would be the FindFirstFile. I need to check, if the caller passed something like ., sample*.cpp or so. My "file system" implementation provides the list of "files names" as a array of char*.

Is there any Windows function or any source code that implements this file name matching?

Answer Source

There are quite a few such functions around. Here's a directory of various implementations, sorted into recursive and non-recursive, etc.

In case you don't like the licensing there (or have trouble with the link, etc.) here's one possible implementation of a matching algorithm that at least closely approximates what Windows uses:

#include <string.h>

bool match(char const *needle, char const *haystack) {
    for (; *needle!='\0'; ++needle) {
        switch (*needle) {
        case '?': ++haystack;   
        case '*': {
            size_t max = strlen(haystack);
            if (needle[1] == '\0' || max == 0)
                return true;
            for (size_t i = 0; i < max; i++)
                if (match(needle+1, haystack + i))
                    return true;
            return false;
            if (*haystack != *needle)
                return false;
    return *haystack == '\0';

Test it online Coliru.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download