Traverse the files and directories under a directory

From CodeCodex

Implementations[edit]

Erlang[edit]

traverse(Dir) ->
    {ok, Cwd} = file:get_cwd(),
    case file:set_cwd(Dir) of
        ok ->
            {ok, Filenames} = file:list_dir("."),
            F = fun(Name) ->
                    case filelib:is_dir(Name) of
                        true  -> traverse(Name);
                        false -> traverse_process(Name)
                    end
                end,
            lists:foreach(F, Filenames);
        {error, Reason} ->
            io:format("~p error reason : ~s~n", [Dir, Reason])
    end,
    file:set_cwd(Cwd).

traverse_process(Name) -> io:format("~s~n", [Name]).

Java[edit]

This example implements methods that recursively visits all files and directories under a directory.

    // Process all files and directories under dir
    public static void visitAllDirsAndFiles(File dir) {
        process(dir);
    
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllDirsAndFiles(new File(dir, children[i]));
            }
        }
    }
    
    // Process only directories under dir
    public static void visitAllDirs(File dir) {
        if (dir.isDirectory()) {
            process(dir);
    
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllDirs(new File(dir, children[i]));
            }
        }
    }
    
    // Process only files under dir
    public static void visitAllFiles(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllFiles(new File(dir, children[i]));
            }
        } else {
            process(dir);
        }
    }

Ruby[edit]

def process(path)
  puts path
end

def traverse(path='.')
  Dir.entries(path).each do |name|
    next  if name == '.' or name == '..'
    path2 = path + '/' + name
    process(path2)
    traverse(path2)  if File.ftype(path2) == "directory"
  end
end

traverse("/work/backup")