File and FTP Interfaces

Recursive file search

Because Lua has an extremely minimal interface, there is no built-in functions for many tasks. However, the os.execute() function can be used to accomplish nearly anything. In this case, we will use it to recursively search through a directory and its subdirectories to find the full path of a specified file, given its name. Here is my function:

-- Does a recursive search of the directory specified
-- by Root, and returns the full path of the file with
-- the name File, if it is found.  Returns nil otherwise.
function findFile(Root, File)
   local OutputFileName = File..'.fs'
   os.execute('dir /S /B "'..Root..
      '" | find "'..File..'" > "'..OutputFileName..'"')

   local OutputFile =
   local FullPath = OutputFile:read()

   return FullPath

This code is written for Windows. The /S flag makes the command search through subdirectories, and the /B flag makes only the plain file paths printed (and no other info on the file). For Posix, the following command will work:

os.execute('find "'..Root..'" | grep "'..File..'" > "'..OutputFileName..'"')

Leave A Comment?