2005-10-24

Unexpected behavior with FindFirstFile...

Recently, a developer was experiencing some odd behavior with MFC's CFileFind class. It seems that it was returning files that didn't match the wildcard pattern specified. The code was something like:
CFileFind finder;
BOOL bWorking = finder.FindFile( "0011????????.xxx" );
while( bWorking )
{
        bWorking = finder.FindNextFile();
        // ...
}

CFileFind uses the Win32 functions FindFirstFile and FindNextFile. After working with various variations on filenames that (to some extent) match the specified pattern, I was able to determine that files with a name of 00117777.xxx were being matched. OK... the doc on MSDN for FindFirstFile MSDN states:
The search includes the long and short file names.

This gave me an idea. I created about 1000 files in the same directory, with a name generated from a format string like 4454%08x, and tested with my sample program. I got some hits in the search for 0011????????.xxx! Turns out, Windows was creating 8.3 filenames for these files, and the generated 8.3 filenames were like 0011d4~1.xxx. The "false positives" were files which had short file names that matched the desired pattern.

The developer is unable to rely solely on the results of the FindNextFile call, and he has to do a sanity check to make sure that every file that CFileCind indicates is a match, is truly what he's looking for.