Expand/Shrink

walk_dir

Definition: object res = walk_dir(sequence st, integer rid, bool subdirs=false, integer my_dir=DEFAULT)
Description: This routine allows each file in directory to be processed one at a time.

st: the starting/root directory path.
rid: the routine_id() of a function that you supply.
subdirs: when true (non-zero), process subdirectories recursively.
my_dir: [optional] the routine_id() of a sorting function that you supply.

Returns: 0: all files were processed,
W_BAD_PATH (-1): invalid directory,
anything else: any non-zero result from rid, which also terminates the walking process.
pwa/p2js: Not supported.
Comments: walk_dir() calls rid once for each file [and optionally the contents of each subdirectory] in st.

The routine that you supply (rid) should accept the path name and dir_entry for each file and subdirectory. It should return 0 to keep going, or non-zero to stop walk_dir().

This mechanism allows you to write a simple function that handles one file at a time, while walk_dir() handles the process of [recursively] walking through all the files and subdirectories.

The path supplied to walk_dir() must not contain wildcards (* or ?).
Only a single directory (and its subdirectories) can be searched at a time.

By default, the files and subdirectories are visited in alphabetical order. To use a different order, set the final my_dir parameter to the routine_id() of a function that sorts the directory entries differently, see the default_dir() function in builtins\file.e for inspiration.

Note that when recursing subdirectories, this routine ignores any W_BAD_PATH which may have occurred as a result of another process deleting things. Should rid return W_BAD_PATH, it will not necessarily terminate the walking process, although it will cease iterating though the list of files in the directory currently being processed.
Example:
function look_at(string path_name, sequence dir_entry)
    printf(1,"%s\\%s: %d\n",{path_name, dir_entry[D_NAME], dir_entry[D_SIZE]})
    return 0 -- keep going
end function
exit_code = walk_dir(`C:\MYFILES`,look_at,true)
Implementation: See builtins\file.e (an autoinclude) for details of the actual implementation.
See Also: routine_id, dir, current_dir