Question marks in wildcard search in Windows

Viewed 51

I am using wildcard characters (? and *) to search for files in Windows in a c++ program with _tfindfirst64 and _tfindnext64. I observed the following code

    TCHAR root[1024] = L"C:/testData/?????_?????.jpg";
    _tfinddata64_t c_file;
    intptr_t hFile = _tfindfirst64(root, &c_file);
    do
    {
        wcout << c_file.name << endl;
    } while (_tfindnext64(hFile, &c_file) == 0);
    _findclose(hFile);

picks up the following files:

12345_---.jpg
12345_12.jpg
12345_12345.jpg

But I was expected the filter would accept only the last one as it means: "5 arbitrary chars followed by '_' followed by another chars with '.jpg'" as described. What would be the correct way to do it?

1 Answers

As you've found, a ? in a file search doesn't require a character to be present, but matching will fail if a character is present that your search string doesn't account for. For example, foo?.txt will match foo.txt, foo1.txt, fooa.txt, and so on, but will not match foo10.txt or foo_abc.txt.

About the only way I know of to work around this is to re-check the result afterward to assure you eliminate any unwanted matches. In this case, it sounds like just comparing the length of the filename with what you expect will suffice.

Related