How to delete an entire directory that is not empty?

I want to clear a temporary place to collect resources. There fileis only del_dir / 1 in the module , for which the directory is empty. But there is no function to get all the files in a directory (with an absolute path)

The source code is the following, how to fix 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.
+4
source share
2 answers

You can delete the directory through the console command using os: cmd, although this is an approximate approach. For unix-like OS, this will be:

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

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

-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]).
+3
source

Erlang ( - ):

-spec rm_rf(file:filename()) -> ok.

rm_rf(Dir) ->
    Paths = filelib:wildcard(Dir ++ "/**"),
    {Dirs, Files} = lists:partition(fun filelib:is_dir/1, Paths),
    ok = lists:foreach(fun file:delete/1, Files),
    Sorted = lists:reverse(lists:sort(Dirs)),
    ok = lists:foreach(fun file:del_dir/1, Sorted),
    file:del_dir(Dir).

- , .

, .

0

All Articles