FindFirstFile matches wildcards that shouldn't match
Asked Answered
M

1

6

On some of my Windows 10 machines, FindFirstFile matches files that definitely should not match. Assume the following program in Delphi:

{$apptype console}
uses Windows;

var
  FindHandle: THandle;
  FindData: WIN32_FIND_DATA;

begin
  FindHandle := FindFirstFile('*.qqq', FindData);
  if FindHandle <> INVALID_HANDLE_VALUE then
  begin
    try
      repeat
        Writeln(PChar(@FindData.cFileName[0]));
      until not FindNextFile(FindHandle, FindData);
    finally
      FindClose(FindHandle);
    end;
  end;
end.

and four files:

a.qqq
b.qqqt
c.qqqx
c.qqq123

The output I expect to get is just a.qqq. But what actually happens is, all four files get printed out. I get the same result with CMD's dir *.qqq, too, so it's not just Delphi doing weird stuff, but PowerShell's dir *.qqq works as expected. What could possibly be causing this behavior? And particularly, if it is some specific settings in the OS (which seems to be indicated by the fact that I don't get this result on all machines, just some), is there something I can do from within my program to enforce the expected behavior regardless of the OS settings?

Mccarter answered 24/6, 2022 at 7:1 Comment(0)
D
9

The reason is that the underlying Windows functions checks the long and the short file names:

The search includes the long and short file names.

You can see that when you add the /X parameter to the dir call in CMD:

dir /X *.qqq

A possible solution is to add another filter check for each found name that only takes the long name.

Actually, that is what Delphi does in TDirectory.GetFiles, making that sometimes a better alternative to the hand written routine.

Downrange answered 24/6, 2022 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.