Erlang Central

Delete a File

From ErlangCentral Wiki

Problem

You want to delete a file.

Solution

Use Erlang's standard function file:delete.


1> file:delete("/this/file/will/soon/be/gone.txt").
ok

The function deletes the file with the given pathname, if it exists, returning ok if a file was deleted successfully, otherwise an error is returned.

Discussion

Note that if you wish to delete a directory, you should use the corresponding function file:del_dir.


2> file:del_dir("/this/dir/will/soon/be/gone").
ok

The function deletes the given directory if it exists, returning ok if successful. An error will be returned if any part of the directory path is not a directory. Unfortunately it will only delete an empty directory.

To delete a non-empty directory the following can be use:


-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]).