简体   繁体   中英

Execute a file using a pattern as the filename

As part of my application I need to give the users the ability to execute files (videos) from my application, but the problem is that the application does not store a list of these files anywhere in the application itself and the only infomation that is known about the file is the directory it's located in and that it must match a specific pattern, which looks like this: * - Ep[0-99] - * where the * character represents any string, integer, unicode character, etc of any length and Ep & - are string literals and finally, the [0-99] is any integer value between 0 and 99.

This sounds like a perfect job for regular expressions, but the problem is regular expressions require a string to match against ahead of time before a match can be found and as previously stated, the application does not store this string anywhere so using RegEx would not work unless I first used something like the FindFirst function to search the directory the files are located in and then iterate over it, loading each of the files names in a variable that RegEx can match against, but I would rather avoid doing things like this if there is an better alternative available.

I have also looked into the MatchesMask function to accomplish this task, but it suffers from the same issue that using regular expressions does so I would appreciate some advice or an alternative to the method I already mentioned above.

There's no getting away from enumerating the contents of the directory. If you must avoid that, for reasons unknown, then your only remaining option is to guess the filenames. If you wish to find them all then you'd need to try every possible filename that matches your pattern. That is not tractable. There are far too many.

Which takes us back to FindFirst or some other directory enumeration scheme. Personally I would use FindFirst directly. It is simple to call, and efficient. In pseudo-code:

retval := FindFirst(TPath.Combine(dir, '*'), 
  faAnyFile and not faDirectory, searchRec);
if retval = 0 then
  try
    repeat
      filename := TPath.Combine(dir, searchRec.Name);
      if MatchesRegex(filename) then
        DoStuff(filename);
    until FindNext(searchRec) <> 0;
  finally
    FindClose(searchRec);
  end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM