Re: How to get list of output of find command of Linux
- Posted by ghaberek (admin) Jul 17, 2017
- 2002 views
I would not recommend using system() to make an external call to find. That method is not portable and should be considered bad practice.
Here is the method I for recursively finding files in a directory without using walk_dir() and without making recursive calls to the same function.
Essentially, we just keep a running queue of the directories we'd like to scan while adding the files found to a list for output.
include std/filesys.e include std/wildcard.e public function get_files( sequence path = current_dir(), sequence name = "*", integer maxdepth = 0 ) -- -- path : directory path to scan -- name : wildcard pattern to look for -- maxdepth : maximum folder depth to scan within path -- integer depth sequence files, queue, item, full_path object items depth = 1 files = {} path = canonical_path( path ) -- push initial path into queue queue = { {path,depth} } while length( queue ) do -- pop an item off the queue item = queue[1] queue = queue[2..$] -- get the queue item values path = item[1] depth = item[2] -- get the directory items items = dir( path ) if atom( items ) then -- error continue end if for i = 1 to length( items ) do item = items[i] if find( item[D_NAME], {".",".."} ) then -- skip these entries continue end if full_path = join_path({ path, item[D_NAME] }) if find( 'd', item[D_ATTRIBUTES] ) then -- is a directory if maxdepth = 0 or depth < maxdepth then -- queue this directory queue = append( queue, {full_path,depth+1} ) end if else -- is a file if wildcard:is_match( name, item[D_NAME] ) then -- add this to the output files = append( files, full_path ) end if end if end for end while return files end function
-Greg