Search code examples
erlang

How to delete the whole directory which is not empty?


I want to clean the temporary for collecting resource. The file module only has del_dir/1 which require the directory is empty. But there is not function the get the all files in the directory (with absolute path")

The source code is as follows, how to correct it?

 delete_path(X)->
    {ok,List} = file:list_dir_all(X), %% <--- return value has no absolute path here
    lager:debug("_229:~n\t~p",[List]),
    lists:map(fun(X)->
                      lager:debug("_231:~n\t~p",[X]),
                        ok = file:delete(X)
                end,List),
    ok = file:del_dir(X),
    ok.

Solution

  • You can delete a directory via console command using os:cmd, though it's a rough approach. For unix-like OS it will be:

    os:cmd("rm -Rf " ++ DirPath).
    

    If you want to delete a non-empty directory using appropriate erlang functions you have to do it recursively. The following example from here shows how to do it:

    -module(directory).
    -export([del_dir/1]).
    
    del_dir(Dir) ->
       lists:foreach(fun(D) ->
                        ok = file:del_dir(D)
                     end, del_all_files([Dir], [])).
    
    del_all_files([], EmptyDirs) ->
       EmptyDirs;
    del_all_files([Dir | T], EmptyDirs) ->
       {ok, FilesInDir} = file:list_dir(Dir),
       {Files, Dirs} = lists:foldl(fun(F, {Fs, Ds}) ->
                                      Path = Dir ++ "/" ++ F,
                                      case filelib:is_dir(Path) of
                                         true ->
                                              {Fs, [Path | Ds]};
                                         false ->
                                              {[Path | Fs], Ds}
                                      end
                                   end, {[],[]}, FilesInDir),
       lists:foreach(fun(F) ->
                             ok = file:delete(F)
                     end, Files),
       del_all_files(T ++ Dirs, [Dir | EmptyDirs]).